分享一個(gè)Linux批量管理腳本--批量建立服務(wù)器之間SSH免密
今天主要介紹一下linux如何批量建立SSH免密的過(guò)程,僅供參考。
一、批量建立ssh私鑰認(rèn)證
1. 編譯安裝expect
expect依賴(lài)于tcl,而linux系統(tǒng)里一般不自帶安裝tcl,所以需要手動(dòng)安裝。
(1) 安裝tcl
- cd /opt/tcl8.4.11/unix
- ./configure
- make && make install
(2) 安裝expect
- cd expect-5.43.0
- ./configure --with-tclinclude=/opt/tcl8.4.11/generic --with-tclconfig=/usr/local/lib/
- make && make install
(3) 測(cè)試
2. 主控端生成公鑰
執(zhí)行ssh-keygen,該命令會(huì)默認(rèn)在~/.ssh/目錄下創(chuàng)建id_rsa、id_rsa.pub兩個(gè)文件,分別為公鑰和私鑰
- ssh-keygen
- cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
3. 相關(guān)腳本
以下均放在/root目錄下
(1) ip.txt
注意前面是IP,后面是密碼,用冒號(hào):分割,如果密碼有冒號(hào)的建議單獨(dú)處理
- IP:密碼
(2) remote_operate.sh
- #!/bin/bash
- #copyright by hwb
- if [ ! -d /root/.ssh ];then
- mkdir /root/.ssh
- fi
- cat /tmp/authorized_keys >> /root/.ssh/authorized_keys
(3) batch_sshkey.sh
- #!/bin/bash
- #copyright by hwb
- for i in `cat ip.txt`
- do
- ip=$(echo "$i"|cut -f1 -d":")
- password=$(echo "$i"|cut -f2 -d":")
- expect -c "
- spawn scp /root/.ssh/authorized_keys /root/remote_operate.sh root@$ip:/tmp/
- expect {
- \"*yes/no*\" {send \"yes\r\"; exp_continue}
- \"*password*\" {send \"$password\r\"; exp_continue}
- \"*Password*\" {send \"$password\r\";}
- }
- "
- expect -c "
- spawn ssh root@$ip "/tmp/remote_operate.sh"
- expect {
- \"*yes/no*\" {send \"yes\r\"; exp_continue}
- \"*password*\" {send \"$password\r\"; exp_continue}
- \"*Password*\" {send \"$password\r\";}
- }
- "
- done
4. 執(zhí)行腳本并測(cè)試
運(yùn)行batch_sshkey.sh腳本