expect语言,解决交互式输入密码的问题1,安装expect
yum install expect -y
2,编写expect脚本
[root@NFS-server tmp]# cat sshexpect.exp
#!/usr/bin/expect
if { $argc != 2 } {
send_user "usage: expect EXPECT.exp file hostn"
exit
}
#define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password "123.com"
spawn ssh-copy-id -i $file "-p 22 root@$host"
expect {
"yes/no" {send "yesr";exp_continue}
"*password" {send "$passwordr"}
}
expect eof
[root@NFS-server tmp]#
3,编写shell调用
[root@NFS-server tmp]# cat 1.sh
#!/bin/sh
. /etc/init.d/functions
for ip in 53 54 55
do
expect sshexpect.exp ~/.ssh/id_dsa.pub 10.0.0.$ip &>/dev/null
if [ $? -eq 0 ];then
action "$ip" /bin/true
else
action "$ip" /bin/false
fi
done
[root@NFS-server tmp]#
4, 测试,给10.0.0.53/55发id_dsa.pub
[root@NFS-server tmp]# expect sshfile.exp ~/.ssh/id_dsa.pub 10.0.0.54
spawn ssh-copy-id -i /root/.ssh/id_dsa.pub -p 22 root@10.0.0.54
The authenticity of host '10.0.0.54 (10.0.0.54)' can't be established.
RSA key fingerprint is b8:e2:26:b5:fb:b4:42:31:11:f8:15:45:71:0b:68:61.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.54' (RSA) to the list of known hosts.
root@10.0.0.54's password:
Now try logging into the machine, with "ssh '-p 22 root@10.0.0.54'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
[root@NFS-server tmp]# ls
1.sh pulse-75mVmxEZuktI sshfile.exp VMwareDnD vmware-root
[root@NFS-server tmp]# vim 1.sh
[root@NFS-server tmp]# vim 1.sh
[root@NFS-server tmp]# mv sshfile.exp sshexpect.exp
[root@NFS-server tmp]# bash 1.sh
53 [ OK ]
54 [ OK ]
55 [ OK ]
5,登录测试
[root@NFS-server tmp]# ssh 10.0.0.53
Last login: Sat Dec 26 09:17:40 2015 from 10.0.0.250
[root@NFS-WEB1 ~]# exit
logout
Connection to 10.0.0.53 closed.
[root@NFS-server tmp]# ssh 10.0.0.54
Last login: Sat Dec 26 02:10:43 2015 from 10.0.0.52
[root@NFS-WEB2 ~]# exit
logout
Connection to 10.0.0.54 closed.
[root@NFS-server tmp]# ssh 10.0.0.55
Last login: Sat Dec 26 02:12:57 2015 from 10.0.0.250
[root@NFS-BACKUP ~]# exit
logout
Connection to 10.0.0.55 closed.
[root@NFS-server tmp]#