#/bin/bash
file=./host-ip.txt
login_failed=./login_failed.log
result_file=./result.txt

# 检查是否提供了要执行的命令
if [ -z "$1" ]; then
    echo "Usage: $0 <command>"
    exit 1
fi

# 清空文件内容
> "$file"
> "$result_file"
> "$login_failed"

# 起始和结束 IP
START_IP="$1"
END_IP="$2"

USER="$3"
PASSWD="$4"

# 提取基地址和起始数字
BASE_IP=$(echo "$START_IP" | cut -d'.' -f1-3)
START_NUM=$(echo "$START_IP" | cut -d'.' -f4)
END_NUM=$(echo "$END_IP" | cut -d'.' -f4)

# 循环生成 IP
for ((i=START_NUM; i<=END_NUM; i++)); do
    echo "$BASE_IP.$i" >> "$file"
done

echo "IP 地址生成完成，结果保存在 $file 中。"

# 要执行的远程命令
remote_command="$5"

# 遍历每一行
for host in `cat $file`; do
    echo "----------------- 执行命令 $host ---------------------"

    # 使用 sshpass 验证登录
    result=`sshpass -p $PASSWD ssh -o StrictHostKeyChecking=no -o ConnectTimeout=3 "$USER@$host" "$remote_command"`

    if [ $? -eq 0 ]; then
        #echo "$host,Success" >> "$OUTPUT_FILE"
        echo "$host 登录成功"
        echo "$host: $result" >> "$result_file"
    else
        echo "$host,Failed,$result" >> "$result_file"
        echo "$host 登录失败"
    fi
done

echo "验证完成，结果保存在 $result_file 中。"

