批量在远程执行命令 (1) |
发布时间: 2012/7/23 19:15:07 |
对于运维来说,同时管理多台机器是很辛苦的事情,特别是CDN运维需要同时重新启动1000台机器的apache的话或者获取所有机器的状态,靠人工一个个上远程机器上去执行非常费劲,为此我写了一个在一台机器上批量在多台机器上执行shell命令的小程序。 这个程序是顺序在各个远程机器上执行命令,并且把远程执行的输出打印出来。 虽然scp命令也可以执行远程命令,但是这个程序还有一个好处就是有超时时间(30秒),当某条命令执行超过30秒后,这个程序会继续执行下一台机器,而远程的机器上的命令还会继续执行完毕。直接使用scp执行远程命令的话必须等命令执行完毕才能退出。 其中用到了expect: 1.multi_scp_shell.sh
#!/bin/bash #author: yifangyou #create time:2011-05-17 #用来通过scp在目标机器批量执行命令 #配置文件格式: #ssh_hosts=("1.1.1.1" "2.2.2.2") #ssh_ports=("22" "22") 这个可以缺省,缺省值为22,或者个数比ssh_hosts少时,使用缺省值 #ssh_users=("root" "root") 这个可以缺省,缺省值为root,,或者个数比ssh_hosts少时,使用缺省值 #ssh_passwords=("323" "222") 这个可以缺省,缺省的话需要从命令行输入,或者个数比ssh_hosts少时,使用命令行输入 #执行:sh multi_scp_shell.sh conf_file_path 'cmd' if [ -z "$2" ] then echo "sh multi_scp_shell.sh conf_file_path 'cmd'"; exit; fi default_ssh_user="root" default_ssh_port="22"; #upload shell script file path scp_upload=scp_upload.sh #configure file path conf_file=$1 #shell command scp_cmd=$2 #判断conf_file配置文件是存在 if [ ! -e "$conf_file" ] then echo "$conf_file is not exists"; exit; fi #read configure file source $conf_file #若是没有在配置文件里提供密码,则在命令行输入 if [ "${#ssh_passwords[@]}" = "0" ] || [ "${#ssh_passwords[@]}" -lt "${#ssh_hosts[@]}" ] then read -p "please input password:" -s default_ssh_password fi success_hosts=""; fail_hosts=""; for((i=0;i<${#ssh_hosts[@]};i++)) do #remote ssh host ssh_host=${ssh_hosts[$i]}; if [ "$ssh_host" != "" ] then #remote ssh port ssh_port=${ssh_ports[$i]}; if [ "$ssh_port" = "" ] then ssh_port=$default_ssh_port; #use default value fi #remote ssh user ssh_user=${ssh_users[$i]}; if [ "$ssh_user" = "" ] then ssh_user=$default_ssh_user; #use default value fi #remote ssh password ssh_password=${ssh_passwords[$i]}; if [ 亿恩科技地址(ADD):郑州市黄河路129号天一大厦608室 邮编(ZIP):450008 传真(FAX):0371-60123888 本文出自:亿恩科技【www.enkj.com】 |