#!/bin/bash
# 测试 HPE16主机的端口开放情况

# 定义目标主机和端口范围
TARGET_HOST="124.158.103.16"
START_PORT=1
END_PORT=60000

# 初始化变量
OPEN_PORTS=()
TOTAL_PORTS=$((END_PORT - START_PORT + 1))
COUNT=0

# 打印扫描信息
echo "======================================"
echo "开始扫描主机: $TARGET_HOST"
echo "扫描端口范围: $START_PORT - $END_PORT"
echo "扫描开始时间: $(date +%Y-%m-%d\ %H:%M:%S)"
echo "======================================"
echo

# 遍历所有端口进行扫描
for PORT in $(seq $START_PORT $END_PORT); do
    # 使用nc命令测试端口，-z 仅扫描不发送数据，-w 1 设置1秒超时
    nc -z -w 1 $TARGET_HOST $PORT > /dev/null 2>&1
    
    # 如果端口开放，记录并输出
    if [ $? -eq 0 ]; then
        echo "✅ 端口 $PORT 已开放"
        OPEN_PORTS+=($PORT)
    fi

    # 进度提示（每1000个端口显示一次）
    COUNT=$((COUNT + 1))
    if [ $((COUNT % 1000)) -eq 0 ]; then
        PERCENT=$((COUNT * 100 / TOTAL_PORTS))
        echo "🔍 扫描进度: $PERCENT% ($COUNT/$TOTAL_PORTS 端口)"
    fi
done

# 输出扫描结果汇总
echo
echo "======================================"
echo "扫描完成时间: $(date +%Y-%m-%d\ %H:%M:%S)"
echo "======================================"
echo "开放的端口列表:"
if [ ${#OPEN_PORTS[@]} -eq 0 ]; then
    echo "   未发现开放的端口"
else
    for PORT in "${OPEN_PORTS[@]}"; do
        echo "   $PORT"
    done
    echo "总计开放端口数: ${#OPEN_PORTS[@]}"
fi
