bash 使用for和while循环在bash中使用telnet进行日志记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11951624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:01:28  来源:igfitidea点击:

logging using telnet in bash using for and while loop

bash

提问by Talespin_Kit

I have a list of ip addresses in a file, to which i need to login in using telnet and execute some commands(the commands are not unique for all machines, so it can not be automated fully.).

我在一个文件中有一个 ip 地址列表,我需要使用 telnet 登录并执行一些命令(这​​些命令不是所有机器唯一的,所以它不能完全自动化。)。

So below is the script to automate the task partially(i.e telnet to the ip address and display the login screen, Once exited from that telnet session, the script should telnet for the next ip address present in the file and so on.

所以下面是部分自动执行任务的脚本(即 telnet 到 ip 地址并显示登录屏幕,一旦退出该 telnet 会话,脚本应该 telnet 文件中存在的下一个 ip 地址,依此类推。

I have written two scripts(both does the same job) to achive the above task, one using forloop and one using whileloop. The script using forloop works fine, where as the script using whileloop quits after logging in to the first ip.

我写了两个脚本(都做同样的工作)来完成上述任务,一个使用for循环,一个使用while循环。使用for循环的脚本工作正常,因为使用while循环的脚本在登录到第一个 ip 后退出。

script using for loop:-

使用 for 循环的脚本:-

for i in `cat host_ip.txt`;
do 
    telnet $i;
done

script using while loop which fails:-

使用 while 循环失败的脚本:-

while read line;
do
   telnet $line ;
done < host_ip.txt

The output of the failed above while loop script is

上面while循环脚本失败的输出是

10.102.10.0
Trying 10.102.10.0...
telnet: connect to address 10.102.10.0: Network is unreachable
10.102.10.1
Trying 10.102.10.1...
Connected to 10.102.10.1.
Escape character is '^]'.
Connection closed by foreign host.

What is wrong with the script which uses while loop?

使用 while 循环的脚本有什么问题?

采纳答案by chepner

In your while loop, standard input has been redirected from a file, and I suspect telnet is also reading from that file via standard input. Try the following:

在您的 while 循环中,标准输入已从文件重定向,我怀疑 telnet 也通过标准输入从该文件中读取。请尝试以下操作:

while read -u 3 line; do
    telnet $line
done 3< host_ip.txt

This uses a file descriptor other than 0 (standard input) to read from the file, preserving standard input for the telnet command.

这使用 0(标准输入)以外的文件描述符从文件中读取,保留 telnet 命令的标准输入。