1

If I am using Python telnetlib, is there a way to close the telnet session if that device does not support nothing to terminate telnet session, so no ctrl+something or quit or anything like that.

I need this so that I could use read.all

mhawke
  • 84,695
  • 9
  • 117
  • 138
Dominik
  • 311
  • 1
  • 4
  • 11
  • I don't have a telnet server handy to check, but try calling `.close()` before the read. – tdelaney Mar 01 '16 at 02:08
  • ...or maybe not. Looking at the source, that isn't going to work. After `import socket` and assuming your session is called `session`, try `session.get_socket().shutdown(socket.SHUT_WR)`. That should convince the other side to terminate its side of the connection. – tdelaney Mar 01 '16 at 02:12
  • Tried it out, but getting this: – Dominik Mar 01 '16 at 21:41
  • 1
    tn.get_socket().shutdown(socket.SHUT_WR) NameError: name 'socket' is not defined "tn" is the neme of the session, but what is "socket"? – Dominik Mar 01 '16 at 21:41
  • 1
    It's the name of the socket module. Import it as shown before the call. – tdelaney Mar 01 '16 at 21:51
  • Ahhhhhh me idiot, it is working thanks I sadly can not give you a check mark for successful solution because it is a comment, can you formulate it as an answer? – Dominik Mar 01 '16 at 21:58

1 Answers1

2

Network sockets let you shutdown write and/or read channels to let the other side know that you have finished that part of the conversation. For a telnet server, shutting down the write channel is an exit. It should finish sending whatever is in the send pipeline and then close the connection completely. That close is an EOF and read_all should return. So, assuming you've already got a connection called tn

tn.get_socket().shutdown(socket.SHUT_WR)
data = tn.read_all()
tn.close()
Community
  • 1
  • 1
tdelaney
  • 73,364
  • 6
  • 83
  • 116