How to check if Telnet connection is still established? using telnetlib

前提是你 提交于 2019-12-10 15:44:23

问题


I'd like to check if a connection using the telnetlib is still up.

The way I do it is to send a ls command and check the answer, but I'm sure there must be a smoother solution.


回答1:


I've got the idea from here, so kudos to them, the code could be something like this

def check_alive(telnet_object):
    try:
        if telnet_object.sock:
            telnet_object.sock.send(telnetlib.IAC + telnetlib.NOP)
            telnet_object.sock.send(telnetlib.IAC + telnetlib.NOP)
            telnet_object.sock.send(telnetlib.IAC + telnetlib.NOP)
            return True
    except:
        pass 

the idea is pretty simple:

  • if the close() was called .sock will be 0, so we do nothing
  • otherwise, we try to send something harmless, that should not interact with what ever the underlying service is, the IAC + NOP was a good candidate. LaterEdit: seems that doing the send only once is not enough, so I just did it 3 times, it's not very professional I know, but ... "if it looks stupid, but it works ... than it's not stupid"
  • if everything goes well we get to the "return True" thous we get our answer, otherwise, the exception will get ignored, and, as there's no return, we will get a None as a response

I've used this method for both direct and proxied(SocksiPy) connections against a couple of Cisco routers



来源:https://stackoverflow.com/questions/37216064/how-to-check-if-telnet-connection-is-still-established-using-telnetlib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!