在某机器上管理其他机器的SHELL脚本

SHELLLINUX2013-12-12 19:59

继续之前免密码使用公钥登录其他机器的文章,这次分享一个在某机器上管理其他机器的SHELL脚本:

#!/bin/bash
# remoterun.sh coding by icyomik on 2013.11.15

test -n "$1" || exit 1 # NO SERVER LIST
test -n "$2" || exit 2 # NO COMMAND TO SEND

short_sep="=============================="
sshcmd="ssh -p 36000 -q"
tmpdir="/tmp/$(date +%y%m%d)"
mktmpdir="mkdir -p ${tmpdir}; cd ${tmpdir}"
cmdstr=${*}
cmdstr=$(echo ${cmdstr#* } |sed 's/;$//g')

echo -e "USE SERVER LIST:\n"${1}
echo -e "CURRENT COMMAND:\n"${cmdstr}"\n"

for dstsrv in `echo "$1" |tr ',' ' '`; do
    ( host_ip=$(echo ${short_sep} ${dstsrv})
    host_msg=$(${sshcmd} ${dstsrv} "${mktmpdir}; ${cmdstr}; exit 0;" 2>&1) 
    echo -e "${host_ip}"'\n'"${host_msg}" ) &
done | col

使用的格式是:./remoterun.sh ip1,ip2,ip3,ip4 'uptime; whoami; pwd'


额外附赠一个查看多个机器负载的SHELL脚本:

#!/bin/bash
# serverload.sh coding by icyomik on 2013.11.16

HOST_FILE="/zone/jtwo/cmd2srv/TOTAL_HOSTS"
LOAD_FILE="/zone/jtwo/pubzone/srvload.txt"

echo -e "==" `date +"%Z [ %Y/%m/%d %H:%M:%S ] %p %A"` "==\n" > $LOAD_FILE
(echo -e "SERV_IP_ADDR ALIAS 1MIN 5MIN 15MIN" && \
cat ${HOST_FILE} |grep -Ev "^\s*$|^\s*#" |awk '{print $1}' |while read ip; do
    echo -e "$(grep $ip ${HOST_FILE} |sed 's/ /,/g;s/,/ /;')" $(ssh -p 36000 -q ${ip} "echo \$(uptime) |awk -F: '{print \$NF}'") &
done |col |sort -rnk 5 |sed 's/, / /g') |column -t >> $LOAD_FILE

TOTAL_HOSTS的内容格式如下:

# GAME:
10.27.35.139 game4 s14
#10.27.35.138 game3
#10.21.84.33 game2 s12
10.27.14.176 game1 s11
# ZOOKEEPER:
10.27.15.48 zoo2
10.27.17.77 zoo1
# WORLD:
10.27.15.44 world1
# YZDD:
10.21.19.22 yzdd1
# TEST(DEBUG):
10.19.16.28 s2
10.12.15.69 s1

原文链接: http://blog.jtwo.me/use-script-to-manage-other-machines-on-a-server