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

标签 python telnetlib

我正在尝试加载包含 IP 地址的文件,通过 telnet 访问它们,发送一些命令并保存输出。我让它正常工作,输出看起来符合预期。

我的问题是,如果文件中存在无法访问且 telnetlib 超时的 IP 地址。然后整个脚本就停止了。 我想忽略超时的 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

最佳答案

如果您特别想捕获套接字超时,您可以执行以下操作...

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

关于python - 让python 3代码在telnetlib超时后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46477205/

相关文章:

python - 在笛卡尔坐标系中计算不规则形状的边界 2D

Python 多个 telnet session

python - 使用Python telnet lib w/o logout命令

python - 与路由器的连接打不开

python - 在 python 中保存 csv 文件,以日期时间作为文件名

python - 如何根据pytorch中另一个张量的值将张量的某个值更改为零?

Python:列表和字符串匹配

python - 如何修复 TypeError : can only concatenate str (not "list") to str

python - 如何在 Python 中使用 telnet 命令来检查远程服务器上的缺失数据流

Python telnetlib 连接到 Scrapy Telnet 以读取统计信息