一条shell命令让多台Linux服务器执行

1、环境

局域网环境有3台Linux服务器,配置host文件

[root@master1 ~]# vim /etc/hosts

192.168.8.201 master1
192.168.8.202 slave1
192.168.8.203 slave2

 

2、配置master1免密码访问slave1和slave2

[root@master1 ~]# cd .ssh/                        # 若没有该目录,请先执行一次ssh  localhost
[root@master1 .ssh]# ssh-keygen -t rsa            # 会有提示,都按回车就可以

#将master1的id_rsa.pub文件的内容追加到slave1和slave2的authorized_keys文件中,内容如下所示:

[root@slave1 ~]# cat ~/.ssh/authorized_keys
ssh-rsa BBAAC4NzaC1yc2EAAAADAQABAAABAQDfHoKNd2gromznR4tdIV5HYoQkZrELNfmzPiy+dlslL1LYVXuPrHvpVpUEbaXXvUf1LbYJWZNc97IeM4Z75WD48vTNaeNf0QqjSdRfA2e48jQKZrewIURfjNGQDsgoAfykKZmGLlY5LgKl/0ofbxIDdxXdUDd3/XaIio5O6vS7N0MUYMk/GXb/OSdSqfbTHY9cR8qmBze7+de1JzT0dzBb3YKb9TDE0HQnycEZG9yoxgylK62SooAwgGlv1HFZKjX9JFmuRHUd4kQJM+Ubi3uDAarGzKcNuM/LyRG7eEZUYHaicGRXZdY6KHsjitz9wkEuUGEuhjahXJvzEmIS7Apd root@master1

 

3、在master1上编写shell脚本

[root@master1 ~]# vim /usr/local/bin/xcall
#!/bin/sh
echo -e "\033[33m---------master1------------\033[0m"
ssh root@master1 "su - root -c \"$*\""
echo -e "\033[33m---------slave1-------------\033[0m"
ssh root@slave1 "su - root -c \"$*\""
echo -e "\033[33m---------slave2-------------\033[0m"
ssh root@slave2 "su - root -c \"$*\""
exit

给xcall文件添加执行权限

[root@master1 ~]# chmod +x /usr/local/bin/xcall

 

4、测试

[root@master1 ~]# xcall.sh ls
posted @ 2018-03-22 20:11  虚幻  阅读(3213)  评论(0编辑  收藏  举报