Search code examples
linuxterminaltelnet

How to keep telnet connection alive from client side


I have a device as a telnet server but drops the connection if no packet is received in 60 seconds, for some reason this behavior cannot be changed. Putty has a feature to send null packets to the server periodically to keep the session alive, which works fine for me. But some times I have to telnet to the device from linux terminal, where putty is not available. So I wonder if it's possible to periodically send null packets with the linux telnet client, or any other way to keep the session alive, or other command line telnet client that could do this.


Solution

  • This is not a perfect solution, but might suffice. Wrap the telnet within an expect script that detects lack of input. It sends the escape sequence control-] to the telnet client to get the command prompt telnet>, and issues the command send nop (no-operation). I assume this is enough to keep the connection alive. If not there are other commands to try.

    #!/usr/bin/expect
    spawn telnet localhost 
    expect "ogin: "
    send "username\r"
    expect "assword:"
    send "mypw\r"
    expect {$ }
    interact timeout 10 {
     log_user 0; send "\x1d"; expect "telnet>" { send "send nop\r" };
     expect "send nop\r\n"; log_user 1 }
    

    Obviously, you need to edit this with the desired hostname, username, password, and expected command prompt. See man expect for the syntax.