2012-11-18 151 views
2

我想通过python3脚本从基于IP地址的hosts.txt文件telnet到路由器。不过,我收到以下错误:python3 telnet socket.gaierror:[Errno 8]节点名称或服务名称提供,或不知道

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

你想从线路使用.strip()hosts文件;否则包含换行符:

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

@Martjin Thanks Martjin。现在就像一个魅力! – gregi22

相关问题