2

I'm trying telnet to routers based on ip addresses from hosts.txt file via python3 script. However I receive the following error:

$ ./telnet_group_1.py  
10.1.1.1  
 Traceback (most recent call last):  
  File "./telnet_group_1.py", line 23, in <module>  
    tn = telnetlib.Telnet(host)  
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/telnetlib.py", line 209, in __init__  
    self.open(host, port, timeout)  
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/telnetlib.py", line 225, in open  
    self.sock = socket.create_connection((host, port), timeout)  
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/socket.py", line 386, in create_connection  
    for res in geta ddrinfo(host, port, 0, SOCK_STREAM):  
socket.gaierror: [Errno 8] nodename nor servname provided, or not known  

If I use the same ip address but defined into the script (not taken from hosts.txt file), script works fine. Please advise how to change the code to make it work ?

Script details:

import telnetlib, socket  

hosts = open("hosts.txt", 'r')  
output = open("output.txt", 'w')  

username = 'admin'  
password = 'admin'  

for h in hosts:  
    host_s = str(h)      
    tn = telnetlib.Telnet(host_s)  
    tn.read_until(b'Username: ')  
    tn.write(username.encode('ascii') + b"\n")  
    tn.read_until(b'Password: ')  
    tn.write(password.encode('ascii') + b"\n")  
    tn.write(b"terminal len 0\n")  
    tn.write(b"show version\n")  
    tn.write(b"exit\n")  
    print(tn.read_all().decode('ascii'), file = output)  

hosts.txt consists only of a single entry as of now - just to make it work:

10.1.1.1  
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
gregi22
  • 21
  • 1
  • 2

1 Answers1

1

You want to use .strip() on the lines from the hosts file; a newline is included otherwise:

for h in hosts:  
    tn = telnetlib.Telnet(h.strip())
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343