python3 telnet socket.gaierror:[Errno 8]提供nodename或servname,或者未知

时间:2012-11-18 11:54:36

标签: python telnet telnetlib

我正在尝试通过python3脚本从hosts.txt文件中基于ip地址telnet到路由器。但是我收到以下错误:

$ ./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  

如果我使用相同的IP地址但在脚本中定义(不是从hosts.txt文件中获取),脚本工作正常。请告知如何更改代码以使其正常工作?

脚本详情:

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目前只包含一个条目 - 只是为了让它起作用:

10.1.1.1  

1 个答案:

答案 0 :(得分:1)

您想在.strip()文件的行中使用hosts;否则包含换行符:

for h in hosts:  
    tn = telnetlib.Telnet(h.strip())