2017-09-28 33 views
1

我試圖直接使用IP地址加載文件,telnet給他們,發送一些命令並保存輸出。我得到它的工作和輸出看起來如預期。讓python 3代碼在telnetlib超時後繼續

我的問題是,如果有一個IP地址在文件中,在無法訪問和telnetlib超時。然後完整的腳本停止。 我想忽略超時的IP地址並繼續處理文件的其餘部分。

#!/usr/bin/env python3 

import pexpect 
import getpass 
import telnetlib 
import socket 

ipfile = input("Enter site (IP address file): ") 
user = input("Enter username: ") 
password = getpass.getpass("Enter password") 
outputfile = ((ipfile)+".output") 

f = open(outputfile, 'w') 
f.write("") 
f.close() 

with open(ipfile) as ips: 
    all_ips = [x.rstrip() for x in ips] # get all ips in a list and strip newline 
for ip in all_ips: 
    tn = telnetlib.Telnet(ip,23,2) 
    tn.read_until(b"Username: ") 
    tn.write(user.encode('ascii') + b"\n") 
    if password: 
    tn.read_until(b"Password: ") 
    tn.write(password.encode('ascii') + b"\n") 
    tn.write(b"term len 0\n") 
    tn.write(b"sh inven\n") 
    tn.write(b"logout\n") 
# print(tn.read_all().decode('ascii')) 
    with open(outputfile,"ab") as f: #write to a file 
     f.write(tn.read_all())      

我得到的錯誤是

Traceback (most recent call last): 
    File "./test4.py", line 22, in <module> 
    tn = telnetlib.Telnet(ip, 23,2) 
    File "/usr/lib/python3.5/telnetlib.py", line 218, in __init__ 
    self.open(host, port, timeout) 
    File "/usr/lib/python3.5/telnetlib.py", line 234, in open 
    self.sock = socket.create_connection((host, port), timeout) 
    File "/usr/lib/python3.5/socket.py", line 711, in create_connection 
raise err 
    File "/usr/lib/python3.5/socket.py", line 702, in create_connection 
    sock.connect(sa) 
socket.timeout: timed out 

回答

1

如果你特別想趕上一個套接字超時,你可以做以下...

import socket 
import telnetlib 

ip = '127.0.0.1' 

try: 
    tn = telnetlib.Telnet(ip, 23, 2) 
except socket.timeout: 
    print("connection time out caught.") 
    # handle error cases here... 
+0

您需要做的唯一事情1.導入套接字模塊。 2.在觸發套接字超時的代碼周圍放置一個「try」「except」塊(看起來像第22行,看着堆棧跟蹤)。 – Kyle

+0

1:導入套接字。完成。 2:我可以把第22行的「嘗試」,這是有道理的。除了我不能確定。如果我把它放在「tn = telnetlib.Telnet(ip,23,2)」下面的第24行中,如果沒有超時,它可以正常工作。我超時發生它再次失敗 – SIMC

0

我想我得到了它。

#!/usr/bin/env python3 

import pexpect 
import getpass 
import telnetlib 
import socket 

ipfile = input("Enter site (IP address file): ") 
user = input("Enter username: ") 
password = getpass.getpass("Enter password: ") 
outputfile = ((ipfile)+".output") 

f = open(outputfile, 'w') 
f.write("") 
f.close() 

with open(ipfile) as ips: 
    all_ips = [x.rstrip() for x in ips] # get all ips in a list and strip newline 
for ip in all_ips: 
try: 
    tn = telnetlib.Telnet(ip,23,2) 
    tn.read_until(b"Username: ") 
    tn.write(user.encode('ascii') + b"\n") 
    if password: 
    tn.read_until(b"Password: ") 
    tn.write(password.encode('ascii') + b"\n") 
    tn.write(b"term len 0\n") 
    tn.write(b"sh inven\n") 
    tn.write(b"logout\n") 
# print(tn.read_all().decode('ascii')) 
    with open(outputfile,"ab") as f: #write to a fil 
     f.write(tn.read_all()) 
except socket.timeout: 
    print((ip)+" timeout")