Spawning an interactive telnet session from a shell script


Question

I'm trying to write a script to allow me to log in to a console servers 48 ports so that I can quickly determine what devices are connected to each serial line.

Essentially I want to be able to have a script that, given a list of hosts/ports, telnets to the first device in the list and leaves me in interactive mode so that I can log in and confirm the device, then when I close the telnet session, connects to the next session in the list.

The problem I'm facing is that if I start a telnet session from within an executable bash script, the session terminates immediately, rather than waiting for input.

For example, given the following code:

$ cat ./telnetTest.sh
#!/bin/bash

while read line
do
        telnet $line
done
$

When I run the command 'echo "hostname" | testscript.sh' I receive the following output:

$ echo "testhost" | ./telnetTest.sh
Trying 192.168.1.1...
Connected to testhost (192.168.1.1).
Escape character is '^]'.
Connection closed by foreign host.
$

Does anyone know of a way to stop the telnet session being closed automatically?

1
11
9/19/2008 9:53:58 AM

Accepted Answer

You need to redirect the Terminal input to the telnet process. This should be /dev/tty. So your script will look something like:

#!/bin/bash

for HOST in `cat`
do
  echo Connecting to $HOST...
  telnet $HOST </dev/tty
done
7
9/19/2008 2:39:32 PM

I think you should look at expect program. It`s present in all modern linux distros. Here is some exmaple script:

#!/usr/bin/expect -f
spawn telnet $host_name
expect {
   "T0>"                {}
   -re "Connection refused|No route to host|Invalid argument|lookup failure"
                        {send_user "\r******* connection error, bye.\n";exit}
   default              {send_user "\r******* connection error (telnet timeout),
 bye.\n";exit}
}
send "command\n"
expect -timeout 1 "something"

spawn command start remote login program (telnet, ssh, netcat etc)

expext command used to... hm.. expect something from remote session

send - sending commands

send_user - to print comments to stdout


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon