使用expect 打通到其他服務器無密碼訪問

由於zabbix對功能,業務監控比較方便,就用zabbix做監控,zabbix唯一的缺點就是需要在每臺服務器上安裝客戶端,即便是幾十臺服務器,一臺一臺做着實繁瑣,何況更多,時間緊急,無密碼登陸通道還沒打通,就準備先打通,再寫腳本來安裝agentd,就選擇了使用except。關於expect語法與使用方法,可以私下交流。

具體腳本如下。

本腳本可以循環服務器ip,完全做到自動化,缺點:服務器密碼保持一致。

#!/bin/bash 

cat >login.exp <<EOF
#!/usr/bin/expect -f

set ip  [lindex \$argv 0]
set password *****************

set timeout 3
spawn ssh -p60022 admin@\$ip ssh-keygen -t rsa;
expect {
  "yes/no" {send "yes\r";exp_continue}
}
expect "admin@\$ip's password:"
set timeout 2
send "\$password\r"
set timeout 2
expect "(/home/admin/.ssh/id_rsa):"
send "\r"
expect {
 "y/n" {send "y\r";exp_continue}
}
expect "(empty for no passphrase):"
send "\r"
expect "Enter same passphrase again:"
send "\r"
set  timeout 10
send "exit\r"
expect eof

set timeout 3
spawn ssh -p60022 admin@\$ip cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys ;
expect {
 "yes/no" {send "yes\r";exp_continue}
}
expect "admin@\$ip's password:"
set timeout 3
send "\$password\r"
set timeout 10
send "exit\r"
expect eof

set timeout 3
spawn scp -P60022 ~/.ssh/authorized_keys admin@\$ip:~/.ssh/authorized_keys;
expect {
 "yes/no" {send "yes\r";exp_continue}
}
expect "admin@\$ip's password:"
set timeout 3
send "\$password\r"
set timeout 10
send "exit\r"
expect eof
EOF

for i in `cat iplist`
do
  expect login.exp $i 
done
說明,iplist 裏面寫入服務器ip地址即可

[root@zabbix admin]# cat iplist 
172.16.8.34
172.16.8.35


另一個工具 sshpass 也可以實現無密碼訪問。

需要編譯安裝,源碼下載地址 http://sourceforge.net/projects/sshpass/

解壓編譯安裝即可

使用:#從命令行方式傳遞密碼

sshpass -p password ssh root@ip          -p後面直接指定密碼

#從文本傳遞密碼

sshpass -f file ssh root@ip   把密鑰寫到file裏即可。

#從環境變量傳遞

export SSHPASS="user_password"

sshpass -e ssh [email protected] 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章