Shell script realizes code sharing of multiple remote hosts executing commands at the same time

Time:2020-11-22

Meet the needs

When operating on a single machine, we will log in to the machine in the way of “SSH IP”. We can write such a tool vssh IP1, IP2 IPN is used to simulate logging in to n servers. After logging in, all operations are equivalent to taking effect on N servers at the same time.

Implementation method

The home page should ensure that you can log in to the remote host through the local public key without password:


ssh-copy-id [-i [identity_file]] [[email protected]]machine

Shell script


#!/bin/bash
# -------------------------------------------------------------------------------
# Author:   Loya.Chen
# 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 [email protected];do 
  if [ $i -eq $# ];then
    break
  fi
  ssh $ip $cmd &> $logfile
  if [ $? -eq 0 ];then
    #((success++))
    success=$(($success+1))
    echo -e "\n3[32m$ip | success 3[0m \n"
    cat $logfile
  else
    ((failed++))
    echo -e "\n3[31m$ip | failed 3[0m\n "
    cat $logfile
  fi
  ((i++))
done
echo -e '\n-------------------------'
echo -e "3[32msuccess: $success | failed: $failed 3[0m"
echo '-------------------------'

Examples


$ 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 
-------------------------

summary

The above is the whole content of this article, I hope the content of this article can bring some help to your study or work, if you have any questions, you can leave a message to exchange, thank you for your support to developeppaer.