expect
是一个自动化交互工具,主要用于在执行命令时与系统进行自动交互,常用于自动化脚本中。当使用 expect
时,如果遇到没有匹配的情况,可以通过设置超时时间(timeout)来处理这种情况,并发送预设的命令。
以下是一个基本的 expect
脚本示例,展示了如何在等待特定输出但没有匹配到时发送一个默认命令:
#!/usr/bin/expect -f
# 设置超时时间为5秒
set timeout 5
# 启动一个交互式程序,例如SSH
spawn ssh user@example.com
# 等待密码提示
expect "password:"
# 如果匹配到密码提示,发送密码
send "yourpassword\r"
# 等待命令提示符
expect "$ "
# 发送一个命令
send "ls -l\r"
# 等待命令执行完毕
expect "$ "
# 如果没有匹配到任何东西,发送默认命令
send "exit\r"
expect eof
在这个脚本中,如果 expect
在等待 "password:" 或者 "$ " 时超时(即5秒内没有匹配到),它将继续执行后面的命令,这里是发送 "exit\r" 命令来退出SSH会话。
如果你想要在没有匹配到任何东西时执行特定的操作,可以使用 exp_continue
命令来重新开始 expect
循环,或者使用 interact
命令来允许手动交互。
例如:
#!/usr/bin/expect -f
set timeout 5
spawn ssh user@example.com
expect {
"password:" {
send "yourpassword\r"
exp_continue
}
"$ " {
send "ls -l\r"
exp_continue
}
timeout {
puts "No match found, sending default command."
send "exit\r"
}
}
expect eof
在这个例子中,如果在等待 "password:" 或者 "$ " 时超时,脚本将打印一条消息并发送 "exit\r" 命令。
请注意,expect
脚本需要根据你的具体需求进行调整。在实际使用中,确保你的脚本安全,特别是在处理密码等敏感信息时。
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云