Skip to content

expect ​


更新于 2023-09-29

用来处理交互的命令
借助Expect, 可以将交互过程写脚本,完成自动交互
例如:ssh登录,ftp登录,telnet登录等。

man文档 ​

详见manpage

安装 ​

shell
sudo apt install except

手册 ​

详见manpage

shell
man expect

常用关键字 ​

关键字描述
expect从进程接收字符串
send用于向进程发送字符串
spawn启动新的进程
interact允许用户交互
exp_continue继续执行当前expect
send_user打印后跟的字符串内容
interact专人人工交互
exit退出expect脚本
eofexpect执行结束, 退出
set定义变量
puts输出变量
set timeout设置超时时间

/usr/bin/expect <<-EOF

expect脚本 ​

expect脚本跟shell脚本基本相同

当使用expect -f时
后续所有内容必须是expect可以识别的命令
不能包含常规shell命令

shell
#! /usr/bin/expect -f
expect eof

若想添加其它shell命令
可以在shell脚本里通过expect <<-EOF形式

shell
#! /usr/bin/sh
/usr/bin/expect <<-EOF
expect eof
EOF
#后续可以跟常规shell脚本

例子 ​

shell
#! /usr/bin/expect -f

# 获取第1个参数
set usr  [lindex $argv 0]
# 获取第2个参数
set ip   [lindex $argv 1]
# 获取第3个参数
set port [lindex $argv 2]
# 设置超时时间
set timeout 30

spawn ssh $usr@$IP:$port
expect {
    "*yes/no" { send "yes\r"; exp_continue}  
    "*password:" { send "$mypassword\r" }
} 
send "exit\r"
expect eof
shell
#! /usr/bin/sh

/usr/bin/expect <<-EOF
set timeout 10

spawn ssh ubuntu@ubuntu.com
expect {
    "*yes/no" { send "yes\r"; exp_continue}  
    "*password:" { send "ubuntu\r" }  
} 
expect "ubuntu*" {send_user "login\n"}
send "ll ./\r"
expect ".*"
send "exit\r"
expect eof
#interact
EOF

echo "done"
shell
#!/bin/sh
password=pwd
expect -c "
  set timeout 2 
  spawn rsync  -u -r -e \"ssh\" --exclude=\"sitemap.xml.gz\" --delete ./html ubuntu@xx.xx.xx.xx:/home/ubuntu
  expect {
	   \"*yes/no*\"      {send \"YES\r\"; exp_continue;}
      \"*password*\" {send \"$password\r\";}
   }
   expect eof"
shell
#! /usr/bin/expect

# 设置超时时间
set timeout 3
# fork一个子进程执行ssh
spawn ssh root@xxx.xxx.xxx.xxx

# 捕获到密码
expect "*password*"
# 输入密码并回车
send "xxxxxx\r"

# 捕获#
expect "*#"
# 进入常用目录下
send "cd /home/wwwroot/default\r"

# 允许用户进行交互
interact

#结束命令
expect eof