Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 查看埠佔用情況:netstat 與 lsof 實戰技巧

編輯:Linux 系統常見問題解答

方法一:netstat -ant 查看所有 TCP 連線

root@debian:/home# netstat -ant
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address         Foreign Address     State
tcp   0      0      127.0.0.1:25          0.0.0.0:*           LISTEN
tcp   0      0      0.0.0.0:33223         0.0.0.0:*           LISTEN
tcp   0      0      127.0.0.1:3306        0.0.0.0:*           LISTEN
tcp   0      0      0.0.0.0:111           0.0.0.0:*           LISTEN
tcp6  0      0      :::80                 :::*                LISTEN
tcp6  0      0      111.111.111.120:80    111.111.111.114:1119 ESTABLISHED
...

關鍵參數:-a 顯示所有連線,-n 數字格式顯示 IP/埠,-t 僅 TCP。常用組合:netstat -tulnp(顯示 PID/程式名,需 root)。

方法二:lsof -i:PORT 精確定位進程

root@debian:/home# lsof -i:80
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2 2301   root    4u  IPv6   7298      0t0  TCP *:http (LISTEN)
apache2 2497 www-data  4u  IPv6   7298      0t0  TCP *:http (LISTEN)
...

root@debian:/home# lsof -i:3306
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
mysqld  2992 mysql  10u  IPv4   9546      0t0  TCP localhost:mysql (LISTEN)

優勢:直接顯示佔用埠的進程 PID、用戶、命令名,便於 kill -9 PID 釋放埠。

進階組合技

  • 查看特定進程開啟的所有埠:lsof -p -i
  • 查看所有監聽埠及對應進程:ss -tulnp(ss 為 netstat 現代替代品,速度更快)。
  • 殺掉佔用 8080 埠的進程:kill -9 $(lsof -t -i:8080)

總結

netstat 適合快速掃描全域連線狀態,lsof 適合精準定位「誰佔用了這個埠」。現代系統建議優先使用 ss(iproute2 套件)替代 netstat,語法相似且效能更佳。

Copyright © Windows教程網 All Rights Reserved