I am working on a script to pull configs from Cisco devices in GNS3. The script should be looping through a text file and slicing the IP & Port from each line into variables. These variable are then fed into the telnet connection as the IP & Port parameters of Telnetlib
.
import telnetlib
#Open file with list of switches
f = open ("C:\ProgramData\ports.txt")
#Telnet to each switch and configure it
for line in f:
linePort = line[10:]
lineIP = line[:-6]
print "Getting running-config " + lineIP + " " + linePort
tn = telnetlib.Telnet(lineIP,linePort)
However using the variables always ends up in an error being thrown (see below) but if I hard code the same values I am able to create the connection without issue. As it works with a hard coded value I tried forcing a string type with str()
on the two variables but it didn't change the result and it still throws the below error.
C:\Users\SomeUser>python %userprofile%\desktop\config.py
Getting running-config 127.0.0.1 5000
Traceback (most recent call last):
File "C:\Users\Michael\desktop\config.py", line 11, in <module>
tn = telnetlib.Telnet(lineIP,linePort)
File "C:\python27amd64\lib\telnetlib.py", line 211, in __init__
self.open(host, port, timeout)
File "C:\python27amd64\lib\telnetlib.py", line 227, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\python27amd64\lib\socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 10109] getaddrinfo failed
The error being thrown is socket.gaierrr: [Errno 10109] getaddrinfo failed
which I have tried looking into but have not been able to find a resolution for that works for me. Given that this process is supposed to be automated and in a loop it is vital to get it working with variable. As such any help that you all could provide would be much appreciated.
I stumbled across the answer to this in another question and it makes me feel like an idiot for the oversight.
When using variables for the parameters of Telnet
the port needs to be an integer. As such the solution was to force it by using int(var)
and then it connected without issue. The now working code is as follows.
import telnetlib
#Open file with list of switches
f = open ("C:\ProgramData\ports.txt")
#Telnet to each switch and configure it
for line in f:
linePort = line[10:]
lineIP = line[:-6]
print "Getting running-config " + lineIP + " " + linePort
tn = telnetlib.Telnet(lineIP,int(linePort))