简体   繁体   中英

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

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.

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.


Better to use BashFAQ #1 best practices for reading through a file:

# 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 _ .

You can use cut to read the first column of the file only:

for hosts in $(cut -d' ' -f1 < /etc/hosts);
do
    echo "jps for $hosts"
    ssh $hosts "uname -a"
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM