netstat(network statistics)是檢視網路狀態的經典工具,雖新版 Linux 推薦 ss,但 netstat 語法普及度高,仍是運維必會。
| 參數 | 含義 | 常用組合 |
|---|---|---|
-a | 顯示所有連線(含 LISTEN) | netstat -a |
-t | 僅顯示 TCP | netstat -at |
-u | 僅顯示 UDP | netstat -au |
-n | 數字格式顯示 IP/埠(不解析域名) | netstat -ant |
-l | 僅顯示監聽狀態 | netstat -ltn |
-p | 顯示 PID/程式名(需 root) | netstat -tnlp |
-r | 顯示路由表 | netstat -rn |
-s | 顯示協定統計 | netstat -s |
-c | 持續刷新(每秒) | netstat -ct |
-e | 顯示擴充資訊(使用者、inode) | netstat -e |
netstat -tnlp # 輸出: # Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name # tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1234/sshd # tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 5678/mysqld
netstat -tn
netstat -tnlp | grep :8080
netstat -an | grep :22 # 或 netstat -tnlp | grep sshd
netstat -rn # Kernel IP routing table # Destination Gateway Genmask Flags MSS Window irtt Iface # 0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 eth0 # 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
netstat -i # 或詳細 netstat -ie
netstat -ct
netstat -s # 輸出包含: # Tcp: # 12345 active connections openings # 123 failed connection attempts # 456 connection resets received # 789 segments retransmitted # Udp: # ... # Ip: # ... # Icmp: # ...
| 特性 | netstat | ss (iproute2) |
|---|---|---|
| 速度 | 較慢(讀 /proc) | 極快(netlink) |
| 功能 | 基礎 | 強大(支援篩選表達式) |
| 相容性 | 所有 Unix | Linux 現代發行版 |
| 常用替換 | netstat -tnlp | ss -tnlp |
建議:新腳本優先使用
ss,舊系統維護繼續用netstat。
熟練 netstat -tnlp、netstat -rn、netstat -s 三大組合,即可應付 90% 網路故障排查場景。