shell腳本實(shí)現(xiàn)同時多臺遠(yuǎn)程主機(jī)執(zhí)行命令的代碼分享
實(shí)現(xiàn)需求
在對單臺機(jī)器做操作時我們會用“ssh ip”的方式登錄到機(jī)器上,可以寫這樣一個工具vssh ip1,ip2,…ipn 來模擬登錄到n 臺服務(wù)器,登錄后所有操作相當(dāng)于同時對n 臺服務(wù)器生效。
實(shí)現(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)文章
輸出執(zhí)行操作和打印日志的shell腳本實(shí)例
下面小編就為大家?guī)硪黄敵鰣?zhí)行操作和打印日志的shell腳本實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03
Linux Shell在目錄下使用for循環(huán)結(jié)合if查找文件的巧用
今天小編就為大家分享一篇關(guān)于Linux Shell在目錄下使用for循環(huán)結(jié)合if查找文件的巧用,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
shell腳本declare命令的用法詳解(聲明變量的屬性和類型)
這篇文章主要介紹了shell腳本declare命令用法(聲明變量的屬性和類型,declare?命令在一般的腳本編寫中并不常用,大多數(shù)情況下直接使用簡單的變量賦值語句即可滿足需求,需要的朋友可以參考下2023-06-06

