bash - ssh登录后期望脚本不执行
问题描述
我正在尝试编写一个期望脚本来:
- 连接到提供用户和密码的远程服务器
- 循环读取每一行的本地文件
- 在远程服务器上为这些行中的每一行执行特定命令
我可以成功实现第 1 步,并用一个简单的场景测试第 3 步,但还不能让它工作。不幸的是,在脚本的第 8 行,在发送密码后,我只是像手动登录的那样登录到服务器(我可以与控制台交互),其余的没有执行。
我该如何规避这个问题?
这是脚本:
#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh -t -t "$user\@$ip"
expect "Password:"
send "$password\r";
expect "NYXOOBPN402(config)$"
send "delete decoders:ASX-Trade24-FIX.mdp\r"
expect "Are you sure you want to delete 'decoders:ASX-Trade24-FIX.mdp' (y/n)?"
send "y\r";
这就是我执行它的方式:
./test_expect.sh 172.18.250.20 admin admin
解决方案
问题是我的期望在第 17 行是不正确的。我应该只输入“*(config)*”而不是“NYXOOBPN402(config)*”,因为在这部分之前有很多文本不匹配。
这是我遇到同样问题的人的最终脚本:
#!/usr/bin/expect
set timeout 9
# Check if the parameters are correct
if {[llength $argv] == 0} {
send_user "Usage: ./test_expect.sh ip username password\n"
exit 1
}
# Read the file with all the decoders names to be deleted
set f [open "decoders.txt"]
set decoders [split [read $f] "\n"]
close $f
# debug mode - very useful:
#exp_internal 1
# Connect to the server
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh -t "$user\@$ip"
expect "Password: "
send "$password\r";
sleep 3
# send ctrl+c since this terminal shows a lot of decoders
#send \x03
expect {
default { send_user "\nCould not find the expected value.\n"; exit 1 }
"*(config)*" {
# Loop through all the decoders
foreach decoder $decoders {
#send_user "Removing $decoder\n"
send "delete decoders:$decoder\r"
expect {
"Are you sure you want to delete*" { send "y\r" }
"*decoder will still be active*" { send_user "\nRemoved $decoder successfully\n" }
"*no such file or directory" { send_user "\nDecoder $decoder already deleted.\n" }
default { send_user "\nNot expected value with $decoder, please debug.\n"; exit 1 }
}
}
}
}
推荐阅读
- reactjs - React Typescript 无法使用通用组件编译
- typescript - Mongoose - 无法访问 createdAt
- javascript - 我的 PUG 文件中没有读取我的 JavaScript 文件。知道为什么这不起作用吗?
- react-native - React Native:如何将弹出模式放入平面列表
- python - 分组后将具有值的行转换为多列
- javascript - 关于函数中变量范围的问题
- c# - 对 API 的调用异步工作,但我需要它运行同步
- javascript - 如何将 ASP.NET Webforms 中中继器内部的 Eval 值传递给 JavaScript 函数
- java - 在 Spring Cloud for AWS SNS 中,在接收 SNS 消息时抛出 java.lang.IllegalArgumentException
- android - 从 Git 和 Android 克隆一个 Android 项目给我这个错误“失败:构建完成,失败 3 次。”