views:

116

answers:

3
cat hosts.txt | while read h; do telnet $h; done

When I run this, it telnets to first host which denies the connection but then exists instead of looping over the other hosts in the file. Why is it exiting the loop after the first host and how can I fix it?

Thanks.

+1  A: 

telnet is interactive. what are you actually wanting to do? If you want to automate "telnet" session, you can use SSH

while read -r host
do
   ssh <options> <commands> "$host"
done <"hosts.txt"
ghostdog74
+3  A: 

That works just fine in my bash:

$ cat hosts.txt
machine1
machine3

$ cat hosts.txt | while read h; do telnet $h; done
Trying 9.190.123.47...
telnet: Unable to connect to remote host: Connection refused
Trying 9.190.123.61...
telnet: Unable to connect to remote host: Connection refused

However, when I connect to a machine that doesn't refuse the connection, I get:

$ cat hosts.txt
machine2
machine1
machine3

$ cat hosts.txt | while read h; do telnet $h; done
Trying 9.190.123.48...
Connected to machine2.
Escape character is '^]'.
Connection closed by foreign host.

That's because I'm actually connecting successfully and all the other host names are being sent to the telnet session. These are no doubt being used to attempt a login, the remaining host names are invalid as user/password and the session is being closed because of that.

If you just want to log in interactively to each system, you can use:

for h in $(cat hosts.txt); do telnet $h 1023; done

which will not capture the rest of the host names into the first successful session.

If you want to truly automate a telnet session, you should look into a tool such as expect or using one of the remoting UNIX tools such as rsh.

paxdiablo
rsh (remote shell) has a history of not being secure. I would recommend ssh.
ghostdog74
+1  A: 

As mentioned previously telnet is an interactive program that expects input.

At a guess all hosts after the first are consumed as input by the first telnet.

It is not clear what your script is trying to do. Perhaps you need to be clearer on what you are trying to do.

Phil Wallach