1、#!/usr/bin/expect

#!/bin/env expect

解释器

2、set timeout 

设置超时时间

set timetout 30 超时时间为30      (-1表示永不超时)

3、spawn 

启动新的进程的spawn后的send和expect命令都是和spawn打开的进程进行交互的。

例如spawn ssh  root@${HOST} 是创建ssh进程,使该命令的交互指令能够被处理

4、expect

判断交互中上传输出是否包含某些字段,如果有则立即返回,如果设置超时会在等待超时后才返回。


expect {
  "hi" { send "You said hi\n"}
  "hello" { send "Hello yourself\n"}
  "bye" { send "That was unexpected\n"}
}

匹配到hi输出hi,匹配到hello输出hello yourself,匹配到bye输出that was unexpected

5、send

接受一个字符串参数,并将该参数发送给进程


5.1、send_error

将结果作为错误输出输出到终端,而不是到进程

5.2、send_user

将结果作为标准输出输出到终端,而不是到进程


6、interact

保持交互状态并将控制权交给控制台,这个时候可以进行手操作。

如果你运行远程登录脚本,没有条脚本完成后会出,而不再保留在远程终端,有这条就是继续在终端操作。


7、#!/usr/bin/expect -d

以DEBUG模式运行脚本,能够获得更多信息


8、 exp_continue

The command exp_continue allows expect itself to continue executing rather than returning as it normally would. 

exp_continue使expect命令继续执行,而不是返回值


9、$argv 参数数组

接收参数,通过 [lindex $argv n] 可以获得第 n 个参数的值,通过 [lrange $argv a b] 可以获取 a-b 的参数值。

#!/usr/bin/expect

set timeout 2 

set username [lindex $argv 0] 

set password [lindex $argv 1] 

set hostname [lindex $argv 2] 

spawn /usr/bin/ssh $username@$hostname

expect {

"yes/no"

{send "yes\r"; exp_continue;}

"Password:"

{send "$password\r";}

}

expect eof


10、expect eof

退出spawn创建的进程

当spawn创建的是一个连接,而不是执行一个单独的命令时需要使用expect eof结束进程,否则进程可能不会正常结束

当执行一个命令时使用expect eof会报错,因为没有进程能够断开

错误:执行一个命令,没有进程断开

expect交互处理命令_expect

expect交互处理命令_expect_02

正确用法

expect交互处理命令_shell_03

expect交互处理命令_expect_04

11、expect使用案例

远程连接执行命令

spawn ssh root@${hostname} "cat /etc/passwd"

expect {

 "*yes/no" { send "yes\r"; exp_continue }

 "*password:" { send "${password}\r"  }

}

远程拷贝文件

spawn scp /root/.ssh/authorized_keys   root@${hostname}:/root/.ssh/

expect {

 "*yes/no" { send "yes\r"; exp_continue }

 "*password:" { send "${password}\r" }

}

创建ssh连接执行多个命令
不要ssh连接后执行多个命令,要执行请写在脚本中执行脚本



异常处理

使用expect加scp传文件时总是少了几个文件,结果对脚本的仔细分析判断,应该是timeout值太小导致的,建议要传文件时timeout值给大点



参考文档:http://blog.csdn.net/jacky0922/article/details/45071817

                 https://www.cnblogs.com/autopenguin/p/5918717.html

官方文档:http://www.tcl.tk/man/expect5.31/expect.1.html#lbAF