Cheug's Blog

当前位置:网站首页 / shell / 正文

扫描主机ip指定端口是否可以访问

2025-07-22 / shell / 221 次围观 / 0 次吐槽 /
#!/bin/bash

input_file="targets.txt"
output_file="check_result.csv"
max_parallel=20
semaphore="/tmp/semaphore.$$"

# 清理输出文件
echo "IP,PORT,RESULT" > "$output_file"

# 初始化信号量控制
mkfifo "$semaphore"
exec 3<>"$semaphore"
rm "$semaphore"

# 初始化20个令牌
for ((i=0; i<$max_parallel; i++)); do
  echo >&3
done

# 清理回车、空行、null 字符
clean_targets=$(tr -d '\000' < "$input_file" | sed 's/\r//' | grep -v '^[[:space:]]*$')

# 遍历每一行 IP:PORT
while IFS= read -r line; do
  # 获取令牌
  read -u 3

  {
    ip=$(echo "$line" | cut -d':' -f1)
    port=$(echo "$line" | cut -d':' -f2)
    
    echo -n "测试 $ip:$port ... "

    timeout 3 bash -c "echo > /dev/tcp/$ip/$port" 2>/dev/null

    if [ $? -eq 0 ]; then
      echo "可访问"
      echo "$ip,$port,OK" >> "$output_file"
    else
      echo "不可访问"
      echo "$ip,$port,FAILED" >> "$output_file"
    fi

    # 归还令牌
    echo >&3
  } &
done <<< "$clean_targets"

# 等待所有任务完成
wait
exec 3>&-

echo "所有端口检查完成,结果已保存到 $output_file"
echo "目标总数:$(wc -l < input_file)"
echo "结果总数:$(($(wc -l < output_file) - 1))"


Powered By Cheug's Blog

Copyright Cheug Rights Reserved.