[英]bash script to execute a command on remote servers is printing the output twice
My input file looks like the below 我的输入文件如下所示
name of the file:/etc/hosts 文件名:/ etc / hosts
10.142.75.6 m1
10.142.75.7 m2
10.142.75.8 m3
The below script looks for the host names in /etc/hosts and should print the output of the command "nproc", but it is printing the output twice, once for the ip and its corresponding host name. 下面的脚本在/ etc / hosts中查找主机名,并应打印命令“ nproc”的输出,但是它将输出两次,一次是ip及其对应的主机名。
for hosts in $(cat /etc/hosts) ;
do
ssh $hosts "uname -a"
done
Presently, you're parsing every word in the file as a hostname -- so you connect to each host first by its IP, and then a second time by its name. 目前,您正在将文件中的每个单词解析为一个主机名-因此,您首先要通过其IP连接到每个主机,然后再通过其名称连接到每个主机。
Better to use BashFAQ #1 best practices for reading through a file: 最好使用BashFAQ#1最佳做法来读取文件:
# read first two columns from FD 3 (see last line!) into variables "ip" and "name"
while read -r ip name _ <&3; do
# Skip blank lines, or ones that start with "#"s
[[ -z $ip || $ip = "#"* ]] && continue
# Log the hostname if we read one, or the IP otherwise
echo "jps for ${name:-$ip}"
# Regardless, connect using the IP; don't allow ssh to consume stdin
ssh "$ip" "uname -a" </dev/null
# with input to FD 3 from /etc/hosts
done 3</etc/hosts
Here, we're putting the first column into the shell variable ip
, the second column (if there is one) into name
, and all subsequent columns into the variable _
. 在这里,我们将第一列放入shell变量
ip
,将第二列(如果存在)放入name
,并将所有后续列放入变量_
。
You can use cut
to read the first column of the file only: 您只能使用
cut
读取文件的第一列:
for hosts in $(cut -d' ' -f1 < /etc/hosts);
do
echo "jps for $hosts"
ssh $hosts "uname -a"
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.