expect解决登录交互问题

2023年 7月 16日 62.3k 0

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]# 

expect.png

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论