判断特定端口是否存在

仅限 tcp 端口

一、 Windows/Winserver

:: @author  wanghuaizhuang
:: @date 2024-2-29
:: @version V1.0

:: get the high risk ports on windows/winserver
:: usage: right-click and run this script as administrator

@echo off
setlocal enabledelayedexpansion

:: set high risk ports
set "ports=21 22 23 25 53 69 110 111 135 139 143 161 389 445 873 1025 1099 1433 1521 2049 2181 2222 2375 2379 2888 3128 3306 3389 3690 3888 4000 4040 4440 4848 4899 5000 5005 5432 5601 5631 5632 5900 5984 6123 6379 7001 7051 7077 7180 7182 7848 8019 8020 8042 8048 8051 8069 8080 8081 8083 8086 8088 8161 8443 8649 8848 8880 8888 9000 9001 9042 9043 9083 9092 9100 9200 9300 9990 10000 11000 11111 11211 18080 19888 20880 25000 25010 27017 27018 28017 50030 50060 50070 50090 60000 60010 60030"

for %%p in (%ports%) do (
netstat -ano | findstr LISTEN | findstr /c:":%%p " >nul
if errorlevel 1 (
echo High Risk Port %%p is not listening. > nul
) else (
echo High Risk Port %%p is listening
set count=0
for /f "tokens=5" %%a in ('netstat -aon ^| findstr ":%%p " ^| findstr "LISTENING"') do (
if !count! equ 0 (
wmic process where processid="%%a" get processid, executablepath
set /a count+=1
)
)
echo "------------------------------------------------------------------"

)
)
pause



参数说明:

  • /c: 完全匹配
  • ":%%p " –> ":139 " (注意空格)避免较长端口号中间包含139
  • errorlevel 1 判断命令执行的返回
  • bat同级目录输出文件

二、 Linux

## get high risk ports on Linux

## @author wanghuaizhuang
## @date 2024-4-8
## @version V2.0

#! /bin/bash

# high-risk ports
valid_ports="21 22 23 25 53 69 110 111 135 139 143 161 389 445 873 1025 1099 1433 1521 2049 2181 2222 2375 2379 2888
3128 3306 3389 3690 3888 4000 4040 4440 4848 4899 5000 5005 5432 5601 5631 5632 5900 5984 6123 6379 7001 7051 7077 7180 7182 7848 8019 8020 8042 8048 8051 8069 8080 8081 8083 8086 8088 8161
8443 8649 8848 8880 8888 9000 9001 9042 9043 9083 9092 9100 9200 9300 9990 10000 11000 11111 11211 18080 19888 20880 25000 25010 27017 27018 28017 50030 50060 50070 50090 60000 60010 60030
"

# get listening ports
ports=$(ss -tuln | awk 'NR>1 {print $5}' | awk -F '[:]' '{print $NF}' | awk '!seen[$0]++')


# iterate through ports
for port in $ports; do
# check whether the port is a high-risk port
if echo "$valid_ports" | grep -q "\<$port\>"; then
# print on terminal and save to file
echo -e 高危端口: "\e[31m$port\e[0m"

pid=$(lsof -i:$port | awk 'NR>1 {print $2}' | head -n 1)
path=$(ps $pid | awk 'NR==2 {print $5}')

echo -e 进程ID: "\e[31m$pid\e[0m"
echo -e 二进制文件: "\e[31m$path\e[0m"
echo -e "----------------\n"
echo "$port" >> output.txt
fi
done