Linux之expect

发布时间 2023-08-20 17:59:55作者: 德国南部之星

目录

[root@localhost ~]#cat <<EOF
> hello
> hi
> halo
> EOF
hello
hi
halo

Expect

  • 建立在tcl上的一个工具
  • 用于自动化控制和测试
  • 解决shell脚本中交互相关问题

/usr/bin/expect

[root@localhost ~]#rpm -q expect
expect-5.45-14.el7_1.x86_64
[root@localhost ~]#which expect
/usr/bin/expect
[root@localhost ~]#vim test
[root@localhost ~]#cat test
#!/usr/bin/expect
spawn ssh 192.168.174.102

expect {
   "yes/no"   {send "yes\r"; exp_continue}
   "password" {send "123123\r" }


}

#expect eof  #交互结束会回到原先的用户
interact  #交互结束保留在目标用户

[root@localhost ~]#chmod +x test
[root@localhost ~]#./test
spawn ssh 192.168.174.102
The authenticity of host '192.168.174.102 (192.168.174.102)' can't be established.
ECDSA key fingerprint is SHA256:8rTcpr5+eXm4qipF2jv/MRbC424mx9Fu/KjVOEIrgVk.
ECDSA key fingerprint is MD5:e2:1d:87:30:df:a2:ca:b0:71:12:42:b3:40:03:77:8f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.174.102' (ECDSA) to the list of known hosts.
root@192.168.174.102's password: 
Last login: Tue Aug 15 18:58:10 2023 from 192.168.174.1

[root@localhost ~]#cat test
#!/usr/bin/expect

set hostname [ lindex $argv 0 ]

spawn ssh $hostname

expect {
   "yes/no"   {send "yes\r"; exp_continue}
   "password" {send "123123\r" }


}

expect eof
#interact
[root@localhost ~]#./test 192.168.174.102
spawn ssh 192.168.174.102
root@192.168.174.102's password: 
Last login: Thu Aug 17 09:41:47 2023 from 192.168.174.100
[root@localhost ~]#
[root@localhost ~]#


  • 定义:是建立在tcl(tool command language)语言基础上的一个工具,常被用于进行自动化控制和测试,解决shell脚本中交互的相关问题

  • Expect概述(与ssh相互配合使用)

    • 建立在tcl之上的工具
    • 用于进行自动化控制和测试
    • 解决shell脚本中交互相关的问题
  • 基本命令

    • 判断上次输出结果中是否包含指定的字符串,如果有则立即返回,否则就等待超时时间后返回
    • 只能捕捉由spawn启动的进程的输出
    • 用于接收命令执行后的输出,然后和期望的字符串匹配
  • send

    • 向进程发送字符串,用于模拟用户的输入
    • 该命令不能自动回车换行,一般要加\r(回车)
  • set

    • 设置超时时间,过期则继续执行后续指令
    • 单位是秒
    • timeout -1表示永不超时
    • 默认情况下,timeout是10秒
  • exp_continue

    • 允许expect继续向下执行指令
  • send_user

    • 回显命令,相当于echo

基本命令:

#脚本解释器
#!/usr/bin/expect(不用.sh结尾)

#spawn 后面通常跟一个Linux执行命令,表示开启一个会话、进程,并跟踪后续交互信息

例:spawn ssh 192.168.8.8

#expect
判断上次输出结果中是否包含指定的字符串,如果有则立即返回,否则就等待超时时间后返回;只能捕捉有swpan启动的进程输出
用于接受命令执行后的输出,然后和期望的字符串匹配

#send
向进程发送字符串,用于模拟用户的输入:该命令不能自动回车换行,一般要加 \r (回车) 或者\n 

```bash
#!/usr/bin/expect

#设置超时时间
set timeout 5

#参数传入
set hostname  [lindex $argv 0]  
#hostname=$1

set password  [lindex $argv 1] 
#password=$2
[root@localhost ~]#rpm -q expect   #先查看是否安装expect,没有安装需要先安装(yum install expect -y)
expect-5.45-14.el7_1.x86_64

[root@localhost ~]#rpm -q tcl
tcl-8.5.13-8.el7.x86_64

[root@localhost ~]#vim test
#!/usr/bin/expect
spawn ssh 192.168.8.106    #启动命令

expect {       #捕捉spawn启动的进程的输出
    "yes/no" { send "yes\r"; exp_continue }  #捕捉yes或no,exp continue代表继续捕捉
    "password" { send "123123\r" }    #继续捕捉

}

#expect eof    #代表结束,结束返回之前终端
interact       #代表结束,留在远程终端

[root@localhost ~]#chmod +x test