在telnetlib超时后让python 3代码继续

时间:2017-09-28 19:50:08

标签: python telnetlib

我尝试加载一个带有IP地址的文件,telnet到它们,发送一些命令并保存输出。我得到它工作,输出看起来像预期的那样。

我的问题是,如果文件中的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

2 个答案:

答案 0 :(得分: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...

答案 1 :(得分: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")