欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

shell腳本實現(xiàn)同時多臺遠(yuǎn)程主機(jī)執(zhí)行命令的代碼分享

 更新時間:2017年03月07日 08:47:23   作者:LoyaChen  
這篇文章主要給大家介紹了關(guān)于shell腳本實現(xiàn)同時多臺遠(yuǎn)程主機(jī)執(zhí)行命令的方法,文中給出了詳細(xì)的代碼示例,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。

實現(xiàn)需求

在對單臺機(jī)器做操作時我們會用“ssh ip”的方式登錄到機(jī)器上,可以寫這樣一個工具vssh ip1,ip2,…ipn 來模擬登錄到n 臺服務(wù)器,登錄后所有操作相當(dāng)于同時對n 臺服務(wù)器生效。

實現(xiàn)方法

首頁要確??梢酝ㄟ^本地公鑰無密碼登錄遠(yuǎn)程主機(jī):

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

shell腳本

#!/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 $@;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 '-------------------------'

示例

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

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論