Linux expect

  expect 是由 Don Libes 基于 Tcl 语言开发并广泛用于交互式操作和自动化测试场景中,通过 expect 可以让 shell脚本无需人为干预自动进行交互式通信。

  expect 的核心功能是根据设定好的匹配形式,以执行相匹配的动作,进入自动化的人机交互。

  以下以Ubantu上Demo做案例说明:

  • 安装 expect
sudo apt-get install expect
  •  实例

  以 SSH 登陆本机在$HOME下创建kitty文件夹作为例子,下面是 shell脚本源码。

#!/usr/bin/expect -f
set timeout 30 set param1 [lindex $argv
0] spawn ssh -p 222 genter@127.0.0.1 expect { "(yes/no)?" {send "yes ";exp_continue} }
expect
"password:" send "a123456 "
expect "@" send "cd /home/genter "
expect "@" send "mkdir $param1 "
expect
"@" send "exit " expect eof

  [#!/usr/bin/expect -f]:告诉操作系统该脚本代码使用 expect 执行

  [set timeout 30]:超时时间,单位:秒。超时脚本将自动向下执行

  [set param1 [lindex $argv 0]]:接收执行shell脚本时传入的参数,参数依次为:$argv 0, 1, 2...

  [spawn ssh -p 222 genter@127.0.0.1]:进行ssh登陆,expect使用 spawn启动脚本和命令会话,这里启动 ssh命令(ssh命令将以子进程方式产生). spawn进程结束后会

    向expect发送eof.

  [expect {"(yes/no)?" {send "yes ";exp_continue}}]:expect命令用于判断上次执行命令的结果中是否包含某字符串,exp_continue表示继续执行下面的匹配

    只有spawn执行命令的结果才会被expect捕捉到,主要包含标准输入提示信息,eof,timeout;

  [expect "password:"  send "a123456 "] :send命令用于执行交互动作,与人工输入密码一样;send会将expect脚本中需要的信息发送到spawn启动的那个进程。

  将上面脚本保存并赋执行权限,执行过程如下:

       

  • 相关错误

  ": no such file or directory :shell脚本中在windows下编辑的,使用了windows中换行符导致。切记:在linux中编辑shell脚本

  • 其他命令

  interact:执行完后保持交互状态,将控制权交给控制台以进行人工操作,如果没有这个命令执行完后会自动退出。

  send_user:send_user用于回显用户发出的消息,类似于shell中的echo

   补充说明:

  1、expect执行速度较慢,如自动输入密码时需要等待一小段时间。

  2、shell脚本需用 ./脚本名 执行,不能用 sh 脚本名,因为 expect 不是用bash执行

  

原文地址:https://www.cnblogs.com/chenyongjun/p/4665644.html