1. expect命令
1.1 expect命令说明
-
spawn:交互程序开始后面跟命令或者指定程序(在壳内启动这个进程)
-
expect:获取匹配信息匹配成功则执行expect后面的程序动作(检测由壳内进程发出的特定交互指令反馈字符串后向下执行)
-
send:用于向进程发送字符串(从壳外向壳内进程发送一条字符串,换行符为确认结束)
-
interact:允许用户交互
-
exp_continue:在expect中多次匹配就需要用到
-
send_user:用来打印输出 相当于shell中的echo
-
exit:退出expect脚本
-
eof:expect执行结束 退出
-
set:定义变量
-
puts:输出变量
-
set timeout:设置超时时间
-
send_tty "$prompt: " # send_tty命令用来实现在终端上显示提示符字串和一个冒号及空格
-
expect_user命令从用户接收消息,当用户输入ctrl+D时结束输入,循环同时结束。
-
expect_out(buffer) # expect_out(buffer)以及expect_out(0,string)及更多输出用法可以查看使用man expect去查看更多细节。
1.2 expect选项
- -c:执行脚本前先执行的命令,可多次使用。
- -d:debug模式,可以在运行时输出一些诊断信息,与在脚本开始处使用exp_internal 1相似。
- -D:启用交换调式器,可设一整数参数。
- -f:从文件读取命令,仅用于使用#!时。如果文件名为"-“,则从stdin读取(使用”./-"从文件名为-的文件读取)。
- -i:交互式输入命令,使用"exit"或"EOF"退出输入状态。
- –:标示选项结束(如果你需要传递与expect选项相似的参数给脚本时),可放到#!行:#!/usr/bin/expect --。
- -v:显示expect版本信息。
1.3. expect实现自动化交互
实现功能如下:
- 远程登录交换设备
- 发送测试命令
- 获取命令的输出结果
#!/usr/bin/expect -f
set timeout 10
set remote_ip [lindex $argv 0] # 将命令行第一个参数保存在remote_ip里
send_tty "send_tty : xxxxxxxxxxxxxxxx\n" # 在终端上显示一段信息
spawn ssh admin@$remote_ip
expect {
"yes/no" { send "yes\r";exp_continue}
"Password:" { send "switch\r" }
}
#set expect_out(0,string) cd
#send_user "\rsend_user : yyyyyyyyyyyyyyyy\r"
#send "$expect_out(1,string)\r"
expect "*> " # 检测交换设备的输出
send "system time\r" # 向交换设备发送命令
expect "*> " # 再次检测交换设备的输出
set result_output $expect_out(buffer) # 将交换设备的输出保存在result_output变量中
puts "\rstart - $result_output -end\r" # 输出捕获到的信息
send "system time\r"
expect "*> "
send "exit\r"
expect eof # 退出expect