赞
踩
在Linux服务器集群以及docker集群或者k8s中,我们通常会在一台主机执行主要操作,有时候需要登录到其他主机执行,就会显得比较麻烦,Ansible就是这么一个在单台服务器操作多台的工具,但是ansible不但需要安装ansible脚本及依赖包,还有比较复杂的指令格式,其实ansible大部分操作可以用以下比较简单的脚本run_cmd来实现:
run_cmd xxxx(你想要在所有主机上执行的指令)
1.在需要执行run_cmd主机使用publickey免密登录所有主机(包括该主机自己),参考之前笔记或者百度,
一只通信旺:零基础docker学习笔记4:免密便捷登录dockerzhuanlan.zhihu.com2. 在该主机新建一个hostlist文件来记录所有需要执行指令的主机ip
- [root@master work]# pwd
- /opt/k8s/work
- [root@master work]# cat hostlist
- 192.168.63.120
- 192.168.63.121
- 192.168.63.122
3. 新建run_cmd脚本如下
- [root@master work]# cat run_cmd
- #!/bin/bash
- run_cmd ()
- {
- local hostlist=`cat /opt/k8s/work/hostlist | awk '{ print $1 }'`;
- for host in $hostlist;
- do
- echo "=============="$host"=============="
- ssh -o StrictHostKeyChecking=no -o ConnectTimeout=2 "$host" $@ ;
- done
- }
- run_cmd $@
4. 添加执行权限
[root@master work]# chmod +x run_cmd
5. 检查脚本是否正常
- [root@master work]# ./run_cmd date
- ==============192.168.63.120==============
- Sun Aug 25 21:26:49 CST 2019
- ==============192.168.63.121==============
- Sun Aug 25 21:26:50 CST 2019
- ==============192.168.63.122==============
- Sun Aug 25 21:26:49 CST 2019
- [root@master work]# ./run_cmd ls -l
- ==============192.168.63.120==============
- total 4
- -rw-------. 1 root root 1425 Aug 21 01:50 anaconda-ks.cfg
- lrwxrwxrwx 1 root root 14 Aug 25 20:05 work -> /opt/k8s/work/
- ==============192.168.63.121==============
- total 8
- -rw-------. 1 root root 1425 Aug 21 01:50 anaconda-ks.cfg
- -rw-r--r--. 1 root root 484 Aug 22 16:22 kubernetes.conf
- ==============192.168.63.122==============
- total 8
- -rw-------. 1 root root 1425 Aug 21 01:50 anaconda-ks.cfg
- -rw-r--r--. 1 root root 484 Aug 23 03:40 kubernetes.conf
- [root@master work]#
6. 把该run_cmd脚本添加到$PATH任意一个目录下,即可在任意目录执行该指令
- [root@master work]# echo $PATH
- /opt/k8s/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
- [root@master work]# cp run_cmd /usr/local/bin
- [root@master work]# ls -l /usr/local/bin/run_cmd
- -rwxr-xr-x 1 root root 279 Aug 25 21:28 /usr/local/bin/run_cmd
- [root@master work]# cd
- [root@master ~]# pwd
- /root
- [root@master ~]# run_cmd date
- ==============192.168.63.120==============
- Sun Aug 25 21:29:46 CST 2019
- ==============192.168.63.121==============
- Sun Aug 25 21:29:46 CST 2019
- ==============192.168.63.122==============
- Sun Aug 25 21:29:46 CST 2019
完成,在此主机上即可对所有主机执行你想执行的指令
喜欢的话用你的小手手点个赞哟^_^
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。