--------------------------------------------------> 代碼以下<----------------------------------------------------------bash
1 #!/bin/bash 2 # 3 # 功能:實現基於SSH密鑰對通訊的主機自動化運維和快速部署 4 # 須知:此腳本目前只實現了,批量SSH無密碼登陸,更多跨主機自動化執行操做,須要後期根據功能寫成函數模塊 5 # 聯繫:QQ-765482322 email:login_532_gajun@sina.com 6 7 # variable define 8 script_path="/etc/keepalived/$(basename $0)" 9 ssh_user=root 10 ssh_passwd="s23gajun" 11 12 # function define 13 check_int(){ 14 local char=$1 15 if [[ $char =~ ^[1-9][0-9]*$ ]];then 16 return 0 17 else 18 return 1 19 fi 20 } 21 22 check_ip(){ 23 local IP=$1 24 valid_check=$(echo "$IP" | egrep "^([0-9][0-9]*\.){3}[0-9][0-9]*$" | awk -F. '{if (NF==4&&($1>=1&&$1<=239)&&($2>=0&&$2<=255)&&($3>=0&&$3<=255)&&($4>=1&&$4<=254))print "yes"}') 25 26 if [[ "$valid_check" == "yes" ]];then 27 active_check=$(wget --connect-timeout=2 -t2 $IP:22 -O /dev/null &> /dev/null;echo $?) 28 if [[ "$active_check" -ne 0 ]];then 29 return 2 30 else 31 return 0 32 fi 33 else 34 return 1 35 fi 36 } 37 38 ssh_keygen(){ 39 /usr/bin/expect << EOF 40 set timeout 5 41 spawn ssh-keygen -t rsa 42 expect { 43 "*save the key*" {send "\n";exp_continue} 44 "Enter passphrase*" {send "\n";exp_continue} 45 "*passphrase again:" {send "\n"} 46 } 47 expect eof 48 EOF 49 50 } 51 52 push_sshkey(){ 53 local host=$1 54 /usr/bin/expect << EOF 55 set timeout 10 56 spawn scp -p /root/.ssh/id_rsa.pub $ssh_user@$host:/root/.ssh/authorized_keys 57 expect { 58 "(yes/no)" {send "yes\n"; exp_continue} 59 "password:" {send "$ssh_passwd\n"} 60 "id_rsa.pub" {puts "(^_^)\n";exit 2\n} 61 } 62 expect eof 63 EOF 64 65 } 66 67 # main 68 read -p "Please enter a number of hosts that need to be operated: " Host_Num 69 echo "=============================================================" 70 71 # 經過函數check_int判斷輸入的字符是否爲整型 72 check_int $Host_Num 73 74 if [ ! $? -eq 0 ];then 75 echo -e "\033[31mError:Not an integer\033[0m" 76 exit 1 77 fi 78 79 # 肯定主機數量後,開始記錄主機的IP地址 80 for i in `seq 0 $[$Host_Num-1]`;do 81 while true;do 82 read -p "Please enter a IP for IP[$i]: " IP[$i] 83 check_ip ${IP[$i]} #調用函數判斷IP地址是否合法,SSH服務是否可用 84 code=`echo $?` 85 if [ $code -eq 0 ];then 86 Host[$i]=${IP[$i]} 87 break 88 elif [ $code -eq 1 ];then 89 echo -e "\033[31mError:IP address not available\033[0m" 90 continue 91 elif [ $code -eq 2 ];then 92 echo -e "\033[31mError:Remote host $IP SSH failed\033[0m" 93 continue 94 95 fi 96 done 97 done 98 99 # 統計可用主機,並顯示給用戶 100 echo -e "================\033[32m[IP Address is as follow]\033[0m=====================" 101 if [ $[${#Host[*]}] -eq 0 ];then 102 echo -e "\033[31mWarning:There is no available target host\033[0m" 103 else 104 for i in `seq 0 $[${#Host[*]}-1]`;do echo "Host[$i] IP: ${Host[$i]}";done 105 fi 106 107 read -p 'Confirm continue to enter [yes], otherwise please restart [r]: ' confirm 108 109 case $confirm in 110 yes) 111 echo -e "================\033[32m[Push public key to remote host]\033[0m===================" 112 ;; 113 r) 114 if [ -f $script_path ];then 115 bash $script_path 116 else 117 echo -e '\033[31mError: please manually modify the value of the script variable "script_path" is correct\033[0m' 118 exit 1 119 fi 120 ;; 121 *) 122 exit 1 123 esac 124 125 # 判斷ssh密鑰對是否存在且有效,只要其中一個不存在就從新生成新的密鑰對 126 if [ ! -f /root/.ssh/id_rsa -o ! -f /root/.ssh/id_rsa.pub ];then 127 \mv -f /root/.ssh/id_rsa{,.bak} &> /dev/null 128 \mv -f /root/.ssh/id_rsa.pub{,.bak} &> /dev/null 129 ssh_keygen 130 131 if [ ! $? -eq 0 ];then 132 echo -e "\033[31mError:Key generation failed\033[0m" 133 exit 1 134 else 135 chmod 600 /root/.ssh/id_rsa.pub 136 fi 137 fi 138 139 # 對SSH的密鑰對作哈希計算,防止私鑰丟失會被篡改 140 [ ! -f /root/.ssh/id_rsa.md5 ] && md5sum /root/.ssh/id_rsa > /root/.ssh/id_rsa.md5 141 [ ! -f /root/.ssh/id_rsa.pub.md5 ] && md5sum /root/.ssh/id_rsa.pub > /root/.ssh/id_rsa.pub.md5 142 md5_chk1=`md5sum -c /root/.ssh/id_rsa.md5 &> /dev/null;echo $?` 143 md5_chk2=`md5sum -c /root/.ssh/id_rsa.pub.md5 &> /dev/null;echo $?` 144 145 # 根據密鑰對判斷是否向遠端主機推送公鑰,並記錄推送密鑰總的次數 146 count=0 147 for i in ${Host[*]};do 148 if [ $[md5_chk1+md5_chk2] -eq 0 ];then 149 push_sshkey $i 150 push_code=`echo $?` 151 if [ $push_code -eq 0 ];then 152 ssh root@$i 'chmod 600 /root/.ssh/authorized_keys' 153 elif [ $push_code -eq 1 ];then 154 echo -e "\033[31mError:Host address $i Key push failed\033[0m" 155 continue 156 elif [ $push_code -eq 2 ];then 157 echo -e "\033[32mUsing the key to login to the remote host $i successfully, no need to push again\033[0m" 158 fi 159 160 let count++ 161 # 對推送的主機狀態結果作日誌,以便統計和查看 162 case $push_code in 163 0) 164 echo "[Time]:`date +'%F-%T'` [Push Host]:$i [Push State]:Success " >> /var/log/push_sshkey.log 165 ;; 166 1) 167 echo "[Time]:`date +'%F-%T'` [Push Host]:$i [Push State]:Failure " >> /var/log/push_sshkey.log 168 ;; 169 2) 170 echo "[Time]:`date +'%F-%T'` [Push Host]:$i [Push State]:Again " >> /var/log/push_sshkey.log 171 esac 172 else 173 echo -e '\033[31mWarning: SSH key change, please delete the "/root/.ssh/id-rsa*", restart this script\033[0m' 174 exit 1 175 fi 176 echo "*-----------------------------------------------------------oo----------------------------------------------*" 177 done 178 179 echo -e "================================\033[32m[Push information statistics]\033[0m=================================" 180 count=${count:-6} 181 tail -n $count /var/log/push_sshkey.log
----------------------------------------------------->演示結果<----------------------------------------------------------併發
說明:運維
1.目前此腳本功能模塊只限於推送密鑰,批量執行某個任務,還要添加功能函數,如今只是個模板,後期我會加上一些基本應用的功能函數ssh
2.此自動化批量執行腳本依賴公鑰驗證,因此請確保你的ssh公鑰訪問沒有問題函數
3.此腳本批量執行一個任務時,並不能作到併發處理,由於我考慮批量執行用的是for循環,不過你能夠經過其餘腳本同時多調用幾回該腳本,也可實現簡單地並行處理this
4.目前此腳本有不少須要改進的地方,但願腳本達人們,以此爲模板擴展模塊功能,你只須要把實現的一個任務寫成函數便可spa
5.指望此腳本也能實現ansible同樣的功能,也能夠經過source提供配置文件,經過一個選項來調用一個功能函數模塊,在此須要你們的共同努力,謝謝rest