首页 文章

检测python的telnetlib中的已关闭连接

提问于
浏览
3

我'm using python' s telnetlib连接到远程telnet服务器 . 我很难检测到连接是否仍处于打开状态,或者远程服务器是否关闭了它 .

我会注意到下次尝试读取或写入时连接已关闭,但希望有办法按需检测它 .

有没有办法在不影响实际连接的情况下发送某种'Are You There'数据包? telnet RFC支持"are you there"和"NOP"命令 - 只是不确定如何让telnetlib发送它们!

3 回答

  • 0

    您应该能够以这种方式发送NOP:

    from telnetlib import IAC, NOP
    
    ... 
    
    telnet_object.sock.sendall(IAC + NOP)
    
  • 3

    继大卫的解决方案之后,在界面上的 close() 之后, sock 属性从 socket._socketobject 变为整数0.如果套接字关闭,对 .sendall 的调用失败并返回 AttributeError ,因此您也可以检查其类型 .

    经过Linux和Windows 7测试 .

  • 0

    我注意到由于某些原因只发送一次是不够的......我偶然“发现它”,我有这样的事情:

    def check_alive(telnet_obj):
        try:
            if telnet_obj.sock: # this way I've taken care of problem if the .close() was called
               telnet_obj.sock.send(IAC+NOP) # notice the use of send instead of sendall
               return True
        except:
               logger.info("telnet send failed - dead")
               pass
    
    # later on
    logger.info("is alive %s", check_alive(my_telnet_obj))
    if check_alive(my_telnet_obj):
         # do whatever
    

    几次运行之后我've noticed that the log message was saying 2993589 , but the code didn' t进入了"if",并且打印了日志消息"telnet send failed - dead",所以在我上一次实现中,正如我所说here,我只是调用了 .send() 方法3次(仅仅是在2的情况下还不够) .

    这是我的2美分,希望它有所帮助

相关问题