加入收藏 | 设为首页 | 会员中心 | 我要投稿 辽源站长网 (https://www.0437zz.com/)- 云专线、云连接、智能数据、边缘计算、数据安全!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

expect实现自动交互由浅入深

发布时间:2021-01-22 00:53:27 所属栏目:Linux 来源:网络整理
导读:h1 id="expect实现自动交互由浅入深"expect实现自动交互由浅入深 作为运维人员可以通过Shell可以实现简单的控制流功能,如:循环、判断等。但是对于需要交互的场合则必须通过人工来干预,有时候我们可能会需要实现和交互程序如telnet服务器等进行交互的功能
命令一般步骤:

启动expect进程(spawn)--> 接收进程字符串(expect) --> 匹配字符串,成功发送字符串(send),否则等待 --> 结束

好了就直接步入主题吧,不扯那些没用的。直接上实例:

[root@localhost shell.sh]# vim test.exp
#!/usr/bin/expect
set timeout 30
spawn ssh -l root 192.168.1.106
expect {
"(yes/no)?" { send "yesr" }
"password:" { send "jiajier" }
}
interact

参数执行该实例:./test.exp

如果报错-bash: ./test.exp: Permission denied,给744权限即可。

[root@localhost shell.sh]# vim test.exp

#!/usr/bin/expect
set ip 192.168.1.106
set user root
set password jiajie
set timeout 30
spawn ssh -l $user $ip
expect {
"(yes/no)?" { send "yesr";exp_continue }
"password:" { send "$passwordr" }
}
interact

set:设置变量,后面直接变量,通过“$变量名”来调用

[root@localhost shell.sh]# vim test.exp 

!/usr/bin/expect

if {$argc!=3} {
send_user "Usage:expect need three arguments:ip user passwordn"
exit 1
}
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 30
spawn ssh -l $user $ip
expect {
"(yes/no)?" { send "yesr";exp_continue }
"password:" { send "$passwordr" }
}
interact

[lindex $argv num]:表示位置参数,从num=0开始

send_user: 打印当前提示,相当于shell里的echo.

[root@localhost shell.sh]# vim test.exp 

!/usr/bin/expect

if {$argc!=3} {
send_user "Usage:expect need three arguments:ip user passwordn"
exit 1
}
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 30
spawn ssh -l $user $ip
expect {
"(yes/no)?" { send "yesr";exp_continue }
"password:" { send "$passwordr" }
}
expect "]#" { send "useradd jjr" }
expect "]#" { send "echo jiajie|passwd --stdin jjr" }
send "exitr"
expect eof
exit -onexit {
send_user "useradd jj is successfully.n"
send_user "Jobs has finished,Goodbye.n"
}

执行后的结果输出:

[root@localhost shell.sh]# ./test.exp 192.168.1.106 root jiajie
spawn ssh -l root 192.168.1.106
root@192.168.1.106's password: 
Last login: Sat Sep  9 03:47:48 2017 from web
[root@localhost ~]# useradd jj
[root@localhost ~]# echo jiajie|passwd --stdin jj
Changing password for user jj.
passwd: all authentication tokens updated successfully.
[root@localhost ~]# exit
logout
Connection to 192.168.1.106 closed.
useradd jj is successfully.
Jobs has finished,Goodbye.

send "exitr":登录出当前环境。

expect eof:结束expect匹配。

exit -onexit{...}:打印结束的提示信息。

[root@localhost shell.sh]# vim test.sh

!/bin/bash

(编辑:辽源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

副标题[/!--empirenews.page--]

<h1 id="expect实现自动交互由浅入深">expect实现自动交互由浅入深

作为运维人员可以通过Shell可以实现简单的控制流功能,如:循环、判断等。但是对于需要交互的场合则必须通过人工来干预,有时候我们可能会需要实现和交互程序如telnet服务器等进行交互的功能。而Expect就使用来实现这种功能的工具。Expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。

安装expect,直接yum install expect -y

解释
解释