Telnet inside a shell script

Vijay picture Vijay · Sep 4, 2012 · Viewed 38.4k times · Source

How can I run telnet inside a shell script and execute commands on the remote server?

I do not have expect installed on my solaris machine because of security reasons. I also do not have the perl net::telnet module installed.

So with out using expect and perl how can I do it?

I tried the below thing but its not working.

#!/usr/bin/sh
telnet 172.16.69.116 <<!
user
password
ls
exit
!

When I execute it, this is what I am getting:

> cat tel.sh
telnet 172.16.69.116 <<EOF
xxxxxx
xxxxxxxxx
ls
exit
EOF
> tel.sh
Trying 172.16.69.116...
Connected to 172.16.69.116.
Escape character is '^]'.
Connection to 172.16.69.116 closed by foreign host.
> 

Answer

crw picture crw · Sep 4, 2012

Some of your commands might be discarded. You can achieve finer control with ordinary script constructs and then send required commands through a pipe with echo. Group the list of commands to make one "session":-

{
sleep 5
echo user
sleep 3
echo password
sleep 3
echo ls
sleep 5
echo exit
} | telnet 172.16.65.209