5

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.

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
r00flr00fl
  • 318
  • 6
  • 16

1 Answers1

0

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

Community
  • 1
  • 1
Lohmar ASHAR
  • 1,639
  • 14
  • 18