How to check if Telnet connection is still establi

2019-06-24 06:22发布

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.

标签: telnetlib
1条回答
\"骚年 ilove
2楼-- · 2019-06-24 07:01

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

查看更多
登录 后发表回答