如何在python telnet中检查服务器是否已关闭或不存在?

问题描述

我正在尝试通过一些 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 块中的命令,这使我的脚本失败。当我手动尝试 telnet 到服务器时,它说:

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')

解决方法

解决此问题的一个简单方法是更改​​ if statement 中的 finally() 以检查是否存在用于连接的打开套接字。

if tn.get_socket():

如果没有打开连接,则返回None

示例


from telnetlib import Telnet

tn = Telnet()

print(type(tn.get_socket()))
#<class 'NoneType'>

tn.open('192.168.0.1')

tn.get_socket()
#<socket.socket fd=764,family=AddressFamily.AF_INET,type=SocketKind.SOCK_STREAM,proto=0,laddr=('192.168.1.1',54489),raddr=('192.168.0.1',23)>

tn.close()

print(type(tn.get_socket()))
#<class 'NoneType'>

来自telnetlib.py

def get_socket(self):
        """Return the socket object used internally."""
        return self.sock