Detect a closed connection in python's telnetlib

冷暖自知 提交于 2019-12-05 14:56:30

You should be able to send a NOP this way:

from telnetlib import IAC, NOP

... 

telnet_object.sock.sendall(IAC + NOP)
Lohmar ASHAR

I've noticed that for some reason sending only once was not enough ... I've "discovered it" by accident, I had something like this:

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

after a few runs I've noticed that the log message was saying "is alive True", but the code didn't entered the "if", and that the log message "telnet send failed - dead" was printed, so in my last implementation, as I was saying here, I'm just calling the .send() method 3 times (just in case 2 were not enough).

That's my 2 cents, hope it helps

Following up on David's solution, after close() on the interface, the sock attribute changes from being a socket._socketobject to being the integer 0. The call to .sendall fails with an AttributeError if the socket is closed, so you may as well just check its type.

Tested with Linux and Windows 7.

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