我使用腳本通過 Telnet 自動登錄并在遠程設備上運行一些命令。但是下面的代碼片段有時不起作用。
這是上述腳本:
expect << EOS
log_user 0;
spawn telnet 192.168.1.51 -l root
expect "#"
send "ls; pwd;\r"
log_user 1;
expect "#"
log_user 0;
send "exit\r"
expect eof
EOS
這是上面的代碼片段運行良好時的輸出:
ls; pwd;
testprogram
/root
這是發生錯誤時的輸出:
send: spawn id exp6 not open
while executing
"send "ls; pwd;\r""
然后我嘗試運行expect -d以獲得額外的除錯輸出。
這-d是啟用時的輸出:
expect version 5.45.3
argv[0] = expect argv[1] = -d
set argc 0
set argv0 "expect"
set argv ""
executing commands from command file
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {95242}
expect: does "" (spawn_id exp6) match glob pattern "#"? no
expect: does "Trying 192.168.1.51...\r\n" (spawn_id exp6) match glob pattern "#"? no
expect: does "Trying 192.168.1.51...\r\nConnected to 192.168.1.51.\r\nEscape character is '^]'.\r\n" (spawn_id exp6) match glob pattern "#"? no
expect: does "Trying 192.168.1.51...\r\nConnected to 192.168.1.51.\r\nEscape character is '^]'.\r\nConnection closed by foreign host.\r\n" (spawn_id exp6) match glob pattern "#"? no
expect: read eof
expect: set expect_out(spawn_id) "exp6"
expect: set expect_out(buffer) "Trying 192.168.1.51...\r\nConnected to 192.168.1.51.\r\nEscape character is '^]'.\r\nConnection closed by foreign host.\r\n"
send: sending "ls; pwd;\r" to { exp6 send: spawn id exp6 not open
while executing
"send "ls; pwd;\r""
更新檢查Connection closed by foreign host.
衷心感謝@glenn jackman。
我添加expect_before到匹配Connection closed by foreign host.一次expect被呼叫。但是又出現了一個問題,Telnet session closed unexpectedly. Please try again.即使這個腳本成功完成它的作業,然后呼叫send "exit\r"; expect eof.
當要呼叫最后一個命令(即)時,有什么方法可以使expect_before不再作業?expectexpect eof
簡單地洗掉expect eof似乎是實作這一目標的一種方式。但據我所知,這不是一個好的解決方案。
expect << EOS
log_user 0;
spawn telnet 192.168.1.51 -l root
expect_before {
"Connection closed by foreign host." {
puts "Telnet session closed unexpectedly."
puts "Please try again."
exit
}
exp_continue
}
expect "#"
send "ls; pwd;\r"
log_user 1;
expect "#"
log_user 0;
send "exit\r"
expect eof
EOS
這是此腳本成功完成其作業(然后呼叫send "exit\r"; expect eof)時的輸出:
ls; pwd;
testprogram
/root
# Telnet session closed unexpectedly.
Please try again.
uj5u.com熱心網友回復:
注意“連接被外部主機關閉”。
spawn telnet 192.168.1.51 -l root
expect {
"Connection closed by foreign host." {
puts "Telnet session closed unexpectedly."
puts "Please try again."
exit
}
"#"
}
使用這種形式的expect命令,expect 正在尋找兩種模式,第一個模式找到了“wins”。
- 如果發生“連接關閉”,則列印訊息并且程式結束
- 如果“#”(你的提示符)出現,沒有具體的動作,所以
expect命令回傳,你的程式的其余部分可以繼續
這種技術對于您經常需要尋找多種模式的高效期望編程至關重要。
展望未來,您可能會隨時看到“連接已關閉”:調查expect_before命令。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492674.html
下一篇:Bash:5分鐘后構建失敗
