
コンテキストとして、私は SSH を使用する複数のマシンのインフラストラクチャを持っています。各マシンの authorized_keys ファイルのおかげで、パスワードなしでマシンに root として SSH 経由で接続できます。インフラストラクチャには定期的に新しいマシンを追加しています。
問題となるのは、次のようなスクリプトを作成することです。
- すべてのマシンに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」を送信します。
私の問題は、2 つの条件 3. と 4. の両方が 1 台のマシンで発生する可能性があり、スクリプトで 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
以下に、expect スクリプトを示します (両方の状況を処理します)。
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
and を削除し、代わりに multiple を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
全ての回答に本当に感謝しています!