SoFunction
Updated on 2025-03-09

Shell scripts implement code sharing of commands executed by multiple remote hosts at the same time

Realize requirements

When operating a single machine, we will use "ssh ip" to log in to the machine. We can write such a tool vssh ip1, ip2,...ipn to simulate logging into n servers. After logging in, all operations are equivalent to taking effect on n servers at the same time.

Implementation method

Home page: Make sure you can log in to the remote host without a password through the local public key:

ssh-copy-id [-i [identity_file]] [user@]machine

shell script

#!/bin/bash
# -------------------------------------------------------------------------------
# Author:   
# Description: Execute commands on multiple remote hosts at the same time.
# -------------------------------------------------------------------------------
set -e
Usage() {
  echo "Usage: $0 host1 host2 ... 'command'"
}
if [ $# -lt 2 ] ;then
  Usage
  exit 0
else
  cmd=${!#}
fi
logfile=$(mktemp)
i=1
success=0
failed=0
for ip in $@;do 
  if [ $i -eq $# ];then
    break
  fi
  ssh $ip $cmd &> $logfile
  if [ $? -eq 0 ];then
    #((success++))
    success=$(($success+1))
    echo -e "\n\033[32m$ip | success \033[0m \n"
    cat $logfile
  else
    ((failed++))
    echo -e "\n\033[31m$ip | failed \033[0m\n "
    cat $logfile
  fi
  ((i++))
done
echo -e '\n-------------------------'
echo -e "\033[32msuccess: $success | failed: $failed \033[0m"
echo '-------------------------'

Example

$ bash vssh 10.0.0.11 10.0.0.12 'free -m'
10.0.0.11 | success 
       total    used    free   shared  buffers   cached
Mem:     2871    156    2715     0     8     36
-/+ buffers/cache:    111    2760
Swap:     2047     0    2047
10.0.0.12 | success 
       total    used    free   shared  buffers   cached
Mem:      980    615    365     0     12     69
-/+ buffers/cache:    533    447
Swap:     2047     0    2047
-------------------------
success: 2 | failed: 0 
-------------------------

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.