45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:怎么样使用shell脚本实现同时多台远程主机执行命令的代码?

怎么样使用shell脚本实现同时多台远程主机执行命令的代码?

2017-06-28 07:47:24 来源:www.45fan.com 【

怎么样使用shell脚本实现同时多台远程主机执行命令的代码?

实现需求

在对单台机器做操作时我们会用“ssh ip”的方式登录到机器上,可以写这样一个工具vssh ip1,ip2,…ipn 来模拟登录到n 台服务器,登录后所有操作相当于同时对n 台服务器生效。

实现方法

首页要确保可以通过本地公钥无密码登录远程主机:

ssh-copy-id [-i [identity_file]] [user@]machine

shell脚本

#!/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 '-------------------------'

示例

$ bash vssh 10.0.0.11 10.0.0.12 'free -m'
10.0.0.11 | success 
    total  used  free  shared buffers  cached
Mem:   2871  156  2715   0   8   36
-/+ buffers/cache:  111  2760
Swap:   2047   0  2047
10.0.0.12 | success 
    total  used  free  shared buffers  cached
Mem:   980  615  365   0   12   69
-/+ buffers/cache:  533  447
Swap:   2047   0  2047
-------------------------
success: 2 | failed: 0 
-------------------------

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对路饭的支持。


本文地址:http://www.45fan.com/a/question/89247.html
Tags: 实现 脚本 shell
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部