美文网首页
expect:免交互自动化ssh

expect:免交互自动化ssh

作者: 风千寻艾 | 来源:发表于2017-11-01 23:09 被阅读0次
#!/usr/bin/expect
set timeout 30
spawn ssh -l root 192.168.0.2
expect "password:"
send "mypaasword\r"
interact

搜索expect相关文章,你多半会遇到上述这段代码示例,具体我就不一行行讲述了,请参加:
https://www.centos.bz/2013/07/expect-spawn-linux-expect-usage/

expect作用

expect用来实现不需人工干预的情况下,自动的和交互式任务进行通信。
比如,在不输入密码的情况下执行一段脚本ssh一台远端机器,本文开头那段代码就是干这个的。

工作原理

expect等待输出中输出特定的字符,然后自动做出响应

基础知识

expect命令可以接受一个字符串参数或者一个正则(-re),用来匹配该参数

$expect_out(buffer)存储了所有对expect的输入,<$expect_out(0,string)>存储了匹配到expect参数的输入

如下程序表示,当expect从标准输入等到hi和换行时,向标准输出发送所有对expect的输入,再发送expect参数hi匹配到的输入

#!/usr/bin/expect
expect "hi\n"
send "you typed <$expect_out(buffer)>"
send "but I only expected <$expect_out(0,string)>"

运行如下:

[root@xxx test]# expect exp.sh 
test1      #input
test2      #input
hi       #input
you typed <test1      #output
test2      #output
hi      #output
>but I only expected <hi      #output

分支匹配

根据不同的输入,做出不同的响应

#!/usr/bin/expect
expect "morning" { send "good morning\n" } \
       "afternoon" { send "good afternoon\n" } \
       "evening" { send "evening\n" }

执行输出如下:

[root@xxx test]# expect exp.sh 
morning      #input
good morning      #output

向expect传递参数

expect接收参数的方式和bash脚本的方式不太一样,bash是通过$0 ... $n 这种方式,而expect是通过set <变量名称> [lindex $argv <param index>]

例如set username [lindex $argv 0],表示将调用该expect脚本的第一个参数($argv0)赋值给变量username

两种特殊情况eof和timeout

  1. eof,一般用于判断spawn启用的进程是否执行完毕
#!/usr/bin/expect
spawn echo "test"
expect {
    "ename:" {send "All\r"}
    eof {send_tty "eof, will exit.\n";exit}
    }
interact

执行上述脚本,spawn启用的进程极短时间内返回eof,expect向终端输出eof, will exit.

[root@xxx test]# expect exp.sh 
spawn echo test
test
eof, will exit.

如果没有eof {send_tty "eof, will exit.\n";exit}这一行,运行程序,会报错

spawn_id: spawn id exp6 not open
    while executing
"interact"

因为此时spawn启动的进程已退出

  1. timeout,当expect期待匹配的字符在设置的超时时间内没匹配上时,执行timeout分支的逻辑
#!/usr/bin/expect
set timeout 5
expect {
    "ename:" {send "All\r"}
    timeout {send_tty "timeout, will exit.\n";exit}
    }

上述脚本,执行输出:

[root@xxx test]# expect exp.sh    #exec and don't input anything
timeout, will exit.      #wait for 5 seconds, output

常用其他命令

Expect中最常用的命令:send,expect,spawn,interact。

send:用于向进程发送字符串
expect:从进程接收字符串
spawn:启动新的进程
interact:允许用户交互

expect和send一般成对搭配使用,spawn用来启用新的进程,spawn后续的expect用来和spawn启用的新进程交互,interact可以理解为暂停自动交互,从而让用户可以手动干预交互过程,比如自动ssh到远程机器,执行interact后,用户可以手动输入命令操作远程机器


Reference
http://www.cnblogs.com/lzrabbit/p/4298794.html
http://hf200012.iteye.com/blog/1866167
http://blog.csdn.net/leexide/article/details/17485451

相关文章

网友评论

      本文标题:expect:免交互自动化ssh

      本文链接:https://www.haomeiwen.com/subject/ccpqpxtx.html