我正在尝试通过 python3 脚本根据 hosts.txt 文件中的 IP 地址远程登录到路由器。但是我收到以下错误:
$ ./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