
對於上下文,我有一個使用 ssh 的多台機器的基礎設施。我們透過 ssh 以 root 身分在機器上連接,無需密碼,感謝每台機器上的authorized_keys 檔案。我們定期在基礎設施中添加新機器。
問題是創建一個腳本:
- 對所有機器執行 Ping 操作(透過解析包含所有機器名稱的檔案)
- 如果 ping 成功,則測試不帶密碼的 ssh 連線(使用指令
ssh -o BatchMode=yes $machine uname -a
) - 如果 ssh 不起作用且是因為此訊息:(
Are you sure you want to continue connecting (yes/no)?
例如,因為這是到此電腦的第一個 ssh 連線),則使用 Expect 腳本傳送“yes” - 如果 ssh 不起作用且是因為要求輸入密碼,則使用 Expect 腳本發送“CTRL + C”
我的問題是, 3. 和 4. 這兩個條件都可能發生在一台機器上,我不知道如何在我的腳本中使用 continue 語句。
這種特定情況是機器要求輸入“是”,但之後也要求輸入密碼。
腳本如下圖所示:
for machine in `cat ${liste} | grep -v \#`
do
ping -c1 ${machine} 2>&1 >/dev/null
if [ $? -eq 0 ]
then
echo ${machine} >> ${pingok}
ssh -o BatchMode=yes ${machine} uname -a &> $verifssh 2>&1
echo $? > ${exitcode}
if grep -q "255" "$exitcode"
then
cut -c 15-74 $verifssh > $verifssh2
if grep "ication failed." "$verifssh2"
then
expect ${scriptexpectknownhosts} ${machine} 2>&1 >/dev/null
continue 3
elif grep "Permission denied (publickey,password,keyboard-interactive)." "$verifssh2"
then
expect ${scriptexpectknownhosts} ${machine} 2>&1 >/dev/null
echo "${machine} -> The machine asks for a password" >> "${sshnok}"
fi
elif grep -q "0" "$exitcode"
then
echo "${machine} works with ssh"
echo "${machine}" >> ${sshok}
fi
else
echo "${machine}" >> "${pingnok}"
fi
done
這是期望腳本(它處理這兩種情況):
set machine [lindex $argv 0]
spawn ssh $machine
expect {
"Are you sure you want to continue connecting (yes/no)? " {send "yes\r";exp_continue}
-exact "Password: " {close}
-re $prompt {send "exit\r";close}
}
簡而言之,我的問題是,對於要求“是”答案然後需要密碼的機器,我想將它們註冊到文件中,${sshnok}
但continue
不起作用。我嘗試了continue
//continue 2
但continue 3
它仍然不想回到上一個循環。
答案1
正如評論中所建議的,我確實放棄了continue
,而不是多個,elif
我只是做了一些更多的if
陳述:
對於機器在cat ${liste} | grep -v \#
do
echo "."
ping -c1 ${machine} 2>&1 >/dev/null
if [ $? -eq 0 ]
then
echo ${machine} >> ${pingok}
ssh -o BatchMode=yes ${machine} uname -a &> $verifssh 2>&1
echo $? > ${exitcode}
if grep -q "255" "$exitcode"
then
cut -c 15-74 $verifssh > $verifssh2
if grep "ication failed." "$verifssh2"
then
expect ${scriptexpectknownhosts} ${machine} 2>&1 >/dev/null
fi
ssh -o BatchMode=yes ${machine} uname -a &> $verifssh 2>&1
cut -c 15-74 $verifssh > $verifssh2
if grep "Permission denied (publickey,password,keyboard-interactive)." "$verifssh2"
then
expect ${scriptexpectknownhosts} ${machine} 2>&1 >/dev/null
echo "${machine} -> Probleme de cle ssh (demande un mdp)" >> "${sshnok}"
fi
ssh -o BatchMode=yes ${machine} uname -a &> $verifssh 2>&1
echo $? > ${exitcode}
if grep -q "0" "$exitcode"
then
echo "${machine}" >> ${sshok}
fi
elif grep -q "0" "$exitcode"
then
echo "${machine}" >> ${sshok}
elif grep -q "1" "$exitcode"
then
echo "wtf 1"
fi
else
echo "${machine}" >> "${pingnok}"
fi
done
非常感謝您的所有回答!