PID 和端口互查:Linux 和 Windows 的常用命令

调试服务、清理端口占用、看某个进程到底连了哪儿——PID 和端口互查是日常操作。整理一份速查。

Linux:按端口找 PID

现代系统首选 ssnetstat 老了,很多发行版默认不装):

ss -lntp | grep :8080

输出:

LISTEN 0 128 *:8080 *:* users:(("java",pid=12345,fd=45))

PID 就是 12345。要看 UDP 加 -u,全协议 ss -tulnp

lsof 也行,输出更清楚:

sudo lsof -i:8080

Linux:按 PID 找端口

ss -tunp | grep "pid=12345"

或者:

sudo lsof -Pan -p 12345 -i

后者会同时列出该进程的所有连接(监听 + 已连接),排查网络问题特别顺手:

COMMAND   PID USER FD TYPE DEVICE  NAME
java    12345 root 45u IPv4      TCP *:8080 (LISTEN)
java    12345 root 46u IPv4      TCP 10.0.0.5:8080->8.8.8.8:443 (ESTABLISHED)

Linux:查所有监听端口

ss -lntp        # TCP
ss -lunp        # UDP
ss -tulnp       # 全部

Windows:按端口找 PID

netstat -ano | findstr :8080

输出最后一列是 PID。看进程名:

tasklist | findstr 12345

PowerShell 版本更直观:

Get-NetTCPConnection -LocalPort 8080 |
  Select-Object LocalAddress, State, OwningProcess |
  Format-Table

Windows:按 PID 找端口

netstat -ano | findstr 12345

PowerShell:

Get-NetTCPConnection | Where-Object OwningProcess -eq 12345

Docker 里的进程

服务在容器里跑,宿主机 ss 只看到 docker-proxy。有两种方式:

宿主机上看容器映射

docker ps --format 'table {{.Names}}\t{{.Ports}}'

进容器里看真实进程

docker exec -it <container> ss -lntp

Windows:把占端口的进程杀掉

一条链:

for /f "tokens=5" %a in ('netstat -ano ^| findstr :8080 ^| findstr LISTENING') do taskkill /PID %a /F

或者 PowerShell:

Get-NetTCPConnection -LocalPort 8080 |
  ForEach-Object { Stop-Process -Id $_.OwningProcess -Force }

Linux:一条命令连查带杀

sudo fuser -k 8080/tcp

fuser 会把所有占用 8080/TCP 的进程直接杀掉,慎用。

一个小坑:找不到 PID

Linux 上 sslsof 有时看不到 PID:

users:(("java",pid=?,fd=?))

多半是没加 sudo——别的用户的进程只有 root 能看。

Windows 上 netstat -ano 看到 PID 4 的东西一般是内核网络栈(System 进程),不是你的应用。

一句话总结

Linux 用 ss -lntp + lsof,Windows 用 netstat -ano + tasklist。PowerShell 用户直接上 Get-NetTCPConnection 更顺。