开发者

Loop exits after first iteration

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 exits instead of looping over the other hosts in the file. Why is it exiti开发者_如何学Pythonng the loop after the first host and how can I fix it?

Thanks.


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.


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜