脚本中Netstat端口查看如何用

wen 实用脚本 9

本文目录导读:

脚本中Netstat端口查看如何用

  1. 查看所有正在监听的端口(Linux/macOS)
  2. 查看特定端口是否被占用(Linux/macOS)
  3. 在脚本中判断端口是否被占用(Linux/macOS)
  4. Windows 系统(CMD/PowerShell)
  5. 常见问题与替代方案
  6. 总结推荐用法:

在脚本中使用 netstat 查看端口,通常有以下几个常见场景,不同操作系统(Linux/Windows/macOS)的 netstat 参数略有不同,但核心逻辑一致。

以下是最常用的几种脚本写法(以 Bash 和 Batch 为例):

查看所有正在监听的端口(Linux/macOS)

# 显示所有监听中的 TCP 和 UDP 端口,不解析主机名(速度快)
netstat -tunlp
# 参数解释:
# -t : TCP
# -u : UDP  
# -n : 显示数字地址和端口(不解析域名)
# -l : 仅显示监听中的端口
# -p : 显示对应的进程PID/名称

查看特定端口是否被占用(Linux/macOS)

# 方法1:直接 grep
netstat -tunlp | grep ":80"
# 方法2:使用 -a 显示所有连接(常用于检查端口是否被用完)
netstat -an | grep ":80"

在脚本中判断端口是否被占用(Linux/macOS)

#!/bin/bash
PORT=8080
if netstat -tunlp | grep -q ":$PORT"; then
    echo "端口 $PORT 已被占用"
else
    echo "端口 $PORT 空闲"
fi

Windows 系统(CMD/PowerShell)

Windows 的 netstat 参数不同,而且没有 grep,需要用 findstrSelect-String

CMD 脚本:

@echo off
rem 查看所有监听端口
netstat -ano | findstr LISTENING
rem 查看特定端口 80 是否被占用
netstat -ano | findstr ":80"
rem 在 bat 中判断端口
netstat -ano | findstr ":8080" >nul
if %errorlevel% equ 0 (
    echo 端口 8080 被占用
) else (
    echo 端口 8080 空闲
)

PowerShell 脚本(推荐,功能更强):

# 查看所有监听端口(显示进程名)
netstat -ano | Select-String "LISTENING"
# 查看特定端口
$port = 8080
$result = netstat -ano | Select-String ":$port"
if ($result) {
    Write-Host "端口 $port 被占用"
} else {
    Write-Host "端口 $port 空闲"
}
# 更现代的 PowerShell 方法(建议用 Get-NetTCPConnection)
Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue

常见问题与替代方案

问题1:netstat 显示不全

  • 某些 Linux 系统(如较新的 Docker 容器)可能没有 netstat,改用 ss
    # ss 是 netstat 的现代替代品,参数类似
    ss -tunlp | grep ":80"

问题2:想要批量检查多个端口

#!/bin/bash
for port in 80 443 8080 3306; do
    netstat -tunlp | grep -q ":$port" && \
        echo "$port: 占用" || echo "$port: 空闲"
done

问题3:输出进程名(Linux/macOS)

# macOS 需要用 sudo 才能显示进程名
sudo netstat -tunlp | grep ":80"
# Linux 上显示进程名(需有权限)
sudo netstat -tunlp | grep ":80"

总结推荐用法:

场景 命令
Linux 快速查看所有监听 netstat -tunlp
Linux 检查某端口 netstat -tunlp \| grep :8080
Linux 脚本判断 netstat -tunlp \| grep -q :8080 && echo 占用
Windows 查看监听 netstat -ano \| findstr LISTENING
通用现代方案(Linux) ss -tunlp
通用现代方案(PS) Get-NetTCPConnection -State Listen

注意:

  • 如果脚本需要自动执行且没有管理员权限,-p 参数可能无法显示进程名,但端口号依然能显示。
  • netstat 在部分精简系统(Alpine Linux、某些容器)中可能不可用,建议考虑 ss 作为备选。

抱歉,评论功能暂时关闭!