Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spawning an interactive telnet session from a shell script

Tags:

bash

telnet

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?

like image 827
Murali Suriar Avatar asked Sep 19 '08 09:09

Murali Suriar


2 Answers

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
like image 79
Dave Webb Avatar answered Jan 03 '23 18:01

Dave Webb


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

like image 33
user11323 Avatar answered Jan 03 '23 17:01

user11323