コンテンツへスキップ

目的
数多のIPがあり複数のパスワード候補の中で、どのパスワードがssh接続できるかを知りたい

問題点
sshpassコマンドで for文を回すとなぜか一回の処理で終わる

解決方法
ssh コマンドに -n オプションを追加して解決した。

参考
https://tech.kurojica.com/archives/36145/

コード例

#!/bin/sh

success_log="success.log"
failure_log="failure.log"
passwords=('password1' 'password2' 'password3')

# ログファイルを初期化
> $success_log
> $failure_log

while read -r ip_address; do
    echo "Attempting login to $ip_address..."

    success=false

    # 3つの異なるパスワードを試行
    for password in "${passwords[@]}"; do
        sshpass -p "$password" ssh -o StrictHostKeyChecking=no -p 32122 -n user@$ip_address "echo 'SSH connection successful!'"
        
        # スクリプトの実行結果に基づいてログを分ける
        if [ $? -eq 0 ]; then
            success=true
            echo "Success: $ip_address (Password: $password)" >> $success_log
            break  # ログイン成功したらループを抜ける
        fi
    done

    # パスワード試行がすべて失敗した場合
    if [ "$success" = false ]; then
        echo "Failure: $ip_address (All Passwords Failed)" >> $failure_log
    fi

done < iplist.txt

echo "Script execution completed."


簡単な解説
passwordsに判別したいパスワードを入力します
その結果は以下に吐き出されます。
success_log="success.log"
failure_log="failure.log"

Success: xxx.xxx.xxx.xxx (Password: password1)