【发布时间】:2021-06-09 01:14:23
【问题描述】:
我正在尝试遍历一些 PDU 服务器以检查条目是否遵循我们的命名约定。
我正在编写一个 python 脚本来检查所有这些服务器。但是,我遇到了一个问题,如果服务器关闭,它会使我的脚本出错并失败。
我不知道如何处理我在一些无法访问或不存在的服务器上遇到的 gaierror。我以为我在“finally”块中处理了它,但显然不是。
这是我的代码。
try:
tn = telnetlib.Telnet()
tn.open(pdu_host)
print(tn.read_until(b'Username: '))
tn.write(PDU_USER + b"\n")
print(tn.read_until(b'Password: '))
tn.write(PDU_PASSWORD + b"\n")
_, _, data = tn.expect([br'Switched .DU:'])
finally:
# close the connection
if tn is not None:
tn.write(b'logout\n')
print(tn.read_all())
tn.close()
print ('logged out')
time.sleep(2) # give the connection time to close
似乎当我收到一个 gaierror 时,tn 不是 None 并且仍然尝试运行 finally 块中的命令,这使我的脚本失败。当我手动尝试远程登录到服务器时,它说:
could not resolve serverX/telnet: Name or service not known
当我的现有代码无法处理此错误情况时,我该如何处理?
编辑:这是我在运行脚本时遇到的错误。
Traceback (most recent call last):
File "check_pdu_outlets.py", line 58, in <module>
tn.write(b'logout\n')
File "/usr/lib/python2.7/telnetlib.py", line 283, in write
self.sock.sendall(buffer)
AttributeError: 'NoneType' object has no attribute 'sendall'
当我通过 pdb 运行脚本并逐行执行代码时,它说我在尝试打开不存在或关闭的服务器时收到 gaierror
-> tn.open(pdu_host)
(Pdb) n
gaierror: (-2, 'Name or service not known')
【问题讨论】:
-
能否包含完整的错误信息?
-
@PacketLoss,感谢您查看我的问题。我已使用收到的错误消息对其进行了更新