Aaron Dhiman Aaron Dhiman - 21 days ago 5
Python Question

Python Socket Substitute Variable for hostname

I have tried various ways to substitute a variable for the hostname into socket.connect call, but I can't get it to work. I am doing the substitution b/c I want to read a list of host IPs from a file and connect to each of them. I have the variable properly formatted as a string with single quotes around it, but it won't connect:

# Connect to the Servers LOOP
with open(sys.argv[2], 'r') as f1:
for server in f1:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server = server.strip('\n')
server = "'%s'" % server
print 'Connecting to ' + server

#connect=s.connect(('10.11.1.229',25))
connect=s.connect((server,25))

# Receive the banner
banner=s.recv(1024)
print banner

s.close


If I hard-code the hostname, it works fine. Execution results in:

Connecting to '10.11.1.8'
Traceback (most recent call last):
File "./connect-loop.py", line 19, in <module>
connect=s.connect((server,25))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -2] Name or service not known


Appreciate any assistance...

Answer

The problem is that you add ticks to the server name (I guess, in order to properly format it when printing it), which are then interpreted when resolving the hostname.

Try with:

with open(sys.argv[2], 'r') as f1:
    for server in f1:
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        server = server.strip('\n')
        print 'Connecting to {} ...'.format(repr(server))

        connect=s.connect((server,25))

        banner=s.recv(1024)
        print repr(banner)

        s.close()

Changes:

  • Format the hostname directly in the print line, and use repr to quote it.
  • Remove the uneeded hostname formatting line
  • Add missing parenthesis to the close() at the end.

Note about repr: it returns the "human representation" of the given value, which, for a string value, is the same string quoted.