[英]Why does my Expect script only echo the command not running?
我正在嘗試自動化一些ssh
過程。 我有我的 Expect 代碼。 但是我的 Expect 代碼只回顯/打印出命令。 它實際上並不運行命令。
#!/usr/bin/expect -f
set timeout 10
set usrnm "aaaaaa"
set pwd "pppppp"
set addr1 "xxx.cloud.xxx.com -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
set addr2 "xxx.xxxx.xxxx.com"
spawn ssh $usrnm@$addr1
expect {
"(yes/no)?" {send "yes\r";exp_continue}
"password: " {send "$pwd\r"}
}
expect "*#"
send "ssh $usrnm@$addr2\r"
expect {
"(yes/no)?" {send "yes\r";exp_continue}
"password:" {send "$pwd\r"}
}
expect "*#"
send "cd /tmp/myself/folder\r"
expect "*#"
send "./run_engine.sh test.py\r"
expect eof
#interact
所以如果我這樣做
expect my_expect.exp
它只是打印命令:
spawn ssh aaaaaa@xxx.cloud.xxx.com -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no (10s later) ssh aaaaa@xxx.xxxx.xxxx.com (10s later) cd /tmp/amz337/COAFALV (10s later) ./run_engine.sh test.py (exit)
我的腳本有什么問題?
因為當變量被替換時,Tcl(以及因此 Expect)不會改變單詞邊界。 您正在嘗試登錄到准確命名的主機:
xxx.cloud.xxx.com -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
空間和所有。
從邏輯上講,將ssh
選項放入保存地址的變量中是沒有意義的。 我可以建議:
set addr1 "xxx.cloud.xxx.com"
set addr2 "xxx.xxxx.xxxx.com"
set ssh_opts($addr1) {-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no}
set ssh_opts($addr2) {}
然后
spawn ssh {*}$ssh_opts($addr1) $usrnm@$addr1
{*}
語法是 Tcl 的“splat”運算符,它將帶有空格的單詞拆分為單個單詞。 參見https://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm規則 #5。
稍后,當您連接到第二台機器時,您將插入一個字符串,因此不需要 splat:
send "ssh $ssh_opts($addr2) $usrnm@$addr2\r"
您可能想要捕獲超時事件並中止腳本:
expect {
timeout {error "timed-out connecting to $addr1"}
"(yes/no)?" {send "yes\r"; exp_continue}
"password: " {send "$pwd\r"}
}
在您的腳本結束時,run_engine 腳本完成后,您仍然連接到 addr2,因此expect eof
不會實際檢測到生成的進程上的 EOF。 您將在 10 秒后超時,並且 Expect 進程將退出。 為了整潔,您應該:
send "./run_engine.sh test.py\r"
expect "*#"
send "exit\r"
# This prompt is from addr1
expect "*#"
send "exit\r"
# _Now_ the spawned ssh process will end
expect eof
如果您認為 run_engine 腳本將花費超過 10 秒的時間,則應在發送該命令之前調整超時變量。
此外,在開發 Expect 腳本時,您應該打開調試:
exp_internal 1
這將向您展示幕后發生的事情,尤其是在查看您的模式是否匹配時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.