Search code examples
pythonsshescapingtelnetparamiko

How to enter the escape characters for telnet programmatically?


I'm using paramiko to ssh into a remote machine, this much seems to be working fine so far

client.connect(hostname, port=ssh_port, username=username, key_filename=key_fname, password=password)

Now from the remote machine I need to go deeper, and using

stdin, stdout, stderr = client.exec_command('telnet localhost %d'%port)

seems to give me the right handles to start talking using stdin.write

My problem is that when I'm done, I don't know how to quit telnet correctly. If I do it manually, I can go into the telnet and I see: Escape character is '^]'. I can use Ctrl+] on the keyboard, and a little menu pops up saying

Console escape. Commands are:

 l  go to line mode
 c  go to character mode
 z  suspend telnet
 e  exit telnet

and then I'm able to quit by pressing 'e' (it quits immediately with no 'enter' key necessary)

But when I try to do this in my script, by stdin.write('^]e'), stdin.write('\^]e'), stdin.write('\c]e'), stdin.write('\M-\C-]e'), etc.. all the time I just see in stdout.read() that my script has entered those characters literally. Putting a little time.sleep(0.1) inbetween the ] and e does not seem to help.

How can I enter that escape sequence programmatically?


Solution

  • Finally I've worked it out.

    The short answer: '\x1d'

    That's the escape sequence to bring up the little menu. I found this via curses module:

    from curses.ascii import ctrl
    print ctrl(']')