实现功能
1.通过脚本,可一次性让集群服务器同时执行一条命令,并返回结果
2.通过脚本,可一次性发送文件或到所有集群服务器
环境:
跳板机:172.16.10.115
服务器1:172.16.20.100
服务器2:172.16.20.200
免密部署:
172.16.10.115
# echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config
生成密钥
# ssh-keygen -t rsa
一路回车,生成免密登录的公钥和私钥
将公钥导入到目标服务器
#ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.16.20.100
#ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.16.20.200
输入密码,导入公钥成功后,ssh连接测试,确保跳板机与目标服务器可以免密登录
执行命令脚本
#cat docmd.sh
#!/bin/bash
IP1=172.16.20.100
IP2=172.16.20.200
...
for i in $IP1 $IP2;
do
if [ "$#" -ne "1" ]
then
echo "please input the cmd,like: ./cmd \"ps aux |grep php\""
exit 1;
else
echo -e "############################################\033[33;1m${i}\033[0m#################################################"
ssh $i $1
if [ "$?" -eq "0" ]; then
echo -e "\033[32;1mcmplete!!!\033[0m"
else
echo -e "\033[31;1mPlease check the command\033[0m"
fi
fi
done
传输文件脚本
#cat scpfile.sh
#!/bin/bash
IP1=172.16.20.100
IP2=172.16.20.200
for i in $IP1 $IP2;
do
if [ ! -n "$1" ] || [ "$#" -gt "2" ]; then
echo "please input the cmd,like: ./scp /root/1.txt /tmp/2.txt"
exit 1;
elif [ -n "$1" ] && [ -n "$2" ]; then
echo -e "############################################\033[33;1m${i}\033[0m#################################################"
rsync -avr $1 root@${i}:${2}
if [ "$?" -eq "0" ]
then
echo -e "\033[32;1msuccess: ${i}:${1} --> ${i}:${2}\033[0m"
else
echo -e "\033[31;1mfailed: ${i}:${1} --> ${i}:${2}\033[0m"
fi
else
echo -e "############################################\033[33;1m$IP1\033[0m#################################################"
rsync -avr $1 root@${i}:${1}
if [ "$?" -eq "0" ]
then
echo -e "\033[32;1msuccess: ${i}:${1} --> ${i}:${1}\033[0m"
else
echo -e "\033[31;1mfailed: ${i}:${1} --> ${i}:${1}\033[0m"
fi
fi
done