Bash – Spawning an interactive telnet session from a shell script

bashtelnet

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?

Best 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