我目前正在嘗試創建一個帶有錯誤處理的腳本。
基本上,該腳本使用以下命令測驗 ssh 連接:
ssh -o BatchMode=yes $machine uname -a
我要處理 3 種潛在情況:
- SSH 無需密碼也能正常作業
- SSH 被阻止,因為機器不在
known_hosts檔案中.ssh - SSH 被阻止,因為機器不在
known_hosts檔案中.ssh并且它需要密碼才能繼續(這意味著id_rsa.pub不在authorized_keys檔案中.ssh
我在呼叫期望腳本的主腳本上是主腳本的樣子:
ssh -o BatchMode=yes ${machine} uname -a &> temp-file.txt 2>&1
# Here we test the ssh connection just once and we store the output of the command in a temp file
if [ $? -eq 255 ]
# If the ssh didn't work
then
if grep -q "Host key verification failed." temp-file.txt
# If the error message is "Host key verification failed."
then
expect script-expect-knownhosts.exp ${machine} 2>&1 >/dev/null
這是script-expect-knownhosts.exp我試圖提出條件的檔案:
#!/usr/bin/expect -f
set machine [lindex $argv 0]
# Here we state that the first argument used with the command will be the $machine variable
set prompt "#|%|>|\$ $"
set timeout 60
spawn ssh $machine
# We do a ssh on the machine
set prompt "#|%|>|\$ $"
expect {
"Are you sure you want to continue connecting (yes/no)? " {send "yes\r";exp_continue}
# If he asks for a yes/no answer, then answer yes to add the machine to the known_hosts file
-exact "Password: " {send -- "^C";exp_continue}
# If he asks for a password, then send a CTRL C
-re $prompt {send "exit\r";exp_continue}
# If the prompt shows up (if after the yes/no question, we don't need to put a password in) then type exit
}
因此,當我在第 2 種情況下使用機器執行期望腳本時會發生以下情況(作業得很好):
spawn ssh machine
Are you sure you want to continue connecting (yes/no)? yes
machine:~ # exit
deconnection
Connection to machine closed.
以下是我在第 3 種情況下使用機器執行期望腳本時發生的情況:
spawn ssh machine
Are you sure you want to continue connecting (yes/no)? yes
Password:
它一直停留在密碼上,直到我手動執行 CTRL C
uj5u.com熱心網友回復:
在情況 2 和 3 中,您不需要exp_continue,因為您正在停止連接程序。
對于案例 2,我認為您真的不想發送 control-C。當您以互動方式執行此操作時,鍵入 control-C 具有發送信號以終止您正在與之互動的行程的效果。你真正想要的是停止這個ssh程序,所以send -- "^C";exp_continue你應該只做close.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/451828.html
上一篇:在檔案中查找串列中只有單詞的行
下一篇:從txt檔案中的讀取行追加
