批量在遠程執(zhí)行命令 (1) |
發(fā)布時間: 2012/7/23 19:15:07 |
對于運維來說,同時管理多臺機器是很辛苦的事情,特別是CDN運維需要同時重新啟動1000臺機器的apache的話或者獲取所有機器的狀態(tài),靠人工一個個上遠程機器上去執(zhí)行非常費勁,為此我寫了一個在一臺機器上批量在多臺機器上執(zhí)行shell命令的小程序。 這個程序是順序在各個遠程機器上執(zhí)行命令,并且把遠程執(zhí)行的輸出打印出來。 雖然scp命令也可以執(zhí)行遠程命令,但是這個程序還有一個好處就是有超時時間(30秒),當某條命令執(zhí)行超過30秒后,這個程序會繼續(xù)執(zhí)行下一臺機器,而遠程的機器上的命令還會繼續(xù)執(zhí)行完畢。直接使用scp執(zhí)行遠程命令的話必須等命令執(zhí)行完畢才能退出。 其中用到了expect: 1.multi_scp_shell.sh
#!/bin/bash #author: yifangyou #create time:2011-05-17 #用來通過scp在目標機器批量執(zhí)行命令 #配置文件格式: #ssh_hosts=("1.1.1.1" "2.2.2.2") #ssh_ports=("22" "22") 這個可以缺省,缺省值為22,或者個數(shù)比ssh_hosts少時,使用缺省值 #ssh_users=("root" "root") 這個可以缺省,缺省值為root,,或者個數(shù)比ssh_hosts少時,使用缺省值 #ssh_passwords=("323" "222") 這個可以缺省,缺省的話需要從命令行輸入,或者個數(shù)比ssh_hosts少時,使用命令行輸入 #執(zhí)行: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 本文出自:億恩科技【prubsntakaful.com】 |