脚本1:需要机器之间免密
ssh-copy-id [-i [identity_file]] [user@]machine
#!/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 '-------------------------'
方法2:这种方式可以不用免密,但是需要在执行命令的机器用户名和密码一致
#!/bin/bash
# -------------------------------------------------------------------------------
# Author: JiangTao.Yu
# 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
sshpass -p "mypasswd" ssh -o "StrictHostKeyChecking no" hduser@$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 '-------------------------'
方法3、从文件读取ip、username、passwd
#!/bin/bash
set -e
success=0
failed=0
while read ip username passwd
do
ip=$ip
username=$username
passwd=$passwd
sshpass -p $passwd ssh -n -o "StrictHostKeyChecking no" $username@$ip "free -m"
if [ $? -eq 0 ];then
success=$(($success+1))
echo -e "\n\033[32m$ip | success\033[0m\n"
else
failed=$(($failed+1))
echo -e "\n\033[32m$ip | failed\033[0m\n"
fi done < ip_user_passwd.txt
echo -e '\n-------------------------'
echo -e "\033[32msuccess: $success | failed: $failed \033[0m"
[root@test ~]# cat ip_user_passwd.txt
192.168.0.235 hduser mypasswd
192.168.4.50 root 123456
192.168.4.50 root 123456