您的位置:首页 > 其它

使用expect 打通到其他服务器无密码访问 推荐

2014-06-05 19:28 302 查看
由于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 user_name@192.168..1.2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  expect   双机互信
相关文章推荐