expect 主要命令 :
参考网站链接:
https://www.cnblogs.com/lixigang/articles/4849527.html
- spawn 新建一个进程,这个进程的交互由 expect 控制
- expect 等待接受进程返回的字符串,直到超时时间,根据规则决定下一步操作
- send 发送字符串给 expect 控制的进程
- set 设定变量为某个值
- exp_continue 重新执行 expect 命令分支
- [lindex $argv 0] 获取 expect 脚本的第 1 个参数
- [lindex $argv 1] 获取 expect 脚本的第 2 个参数
- set timeout -1 设置超时方式为永远等待
- set timeout 30 设置超时时间为 30 秒
- interact 将脚本的控制权交给用户,用户可继续输入命令
- expect eof 等待 spawn 进程结束后退出信号 eof
一、将 expect 嵌套到 shell 脚本中自动登录
,使用“-c”选项,从命令行执行 expect 脚本,expect 可以让你使用“-c”选项,直接在命令行中执行它
#!/bin/bash
FW="192.168.100.1"
for FW in $FW
do
expect -c "
set timeout -1
spawn ssh limi@${FW}
expect {
\"*assword\" {send \"qwe*123456\r\";}
\"yes/no\" { send \"yes\r\"; exp_continue }
}
expect \"*>\" { send \"display interface brief\r\" }
send \"quit\r\"
expect eof
"
done
二、相关解释
#!/usr/bin/expect -f set timeout -1 //永远等待,不会超时 spawn ssh limi@192.168.100.1 //spawn 后面跟命令名称和参数 //如果匹配到*assword,那么发送密码,并进入下面的expect语句(uname -a语句)。 //如果匹配到yes/no,那么发送yes,并重新执行这个expect语句。 expect { "*assword" {send "qwe*123456\r";} "yes/no" {send "yes\r";exp_continue} } //匹配到*>,那么运行防火墙对应命令 expect "*>" {send "display interface brief\r"} send "quit\r" expect eof
三、生产中使用此脚本登陆网络设备自动上传当前配置信息到 FTP 服务器。😰
#!/usr/bin/expect -f set timeout -1 spawn ssh cuijianzhe@192.168.51.1 expect { "*assword" {send "qwe*123456\r";} "yes/no" {send "yes\r";exp_continue} } expect "*>" {send "ftp 192.168.51.202\r"} send "ftp01\r" send "598941324\r" send "put vrpcfg.zip\r" send "quit\r" expect eof
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于