如何使用 Netstat 检查 Linux 中的 TCP 连接状态
TCP(传输控制协议)是一个标准,定义了如何
Linux 中的 TCP 状态
下面是可以在 Linux 上使用 netstat 或 ss 命令查看的 TCP 连接状态列表。
ESTABLISHED
The socket has an established connection.
SYN_SENT
The socket is actively attempting to establish a connection.
SYN_RECV
A connection request has been received from the network.
FIN_WAIT1
The socket is closed, and the connection is shutting down.
FIN_WAIT2
Connection is closed, and the socket is waiting for a shutdown
from the remote end.
TIME_WAIT
The socket is waiting after close to handle packets still in
the network.
CLOSE The socket is not being used.
CLOSE_WAIT
The remote end has shut down, waiting for the socket to close.
LAST_ACK
The remote end has shut down, and the socket is closed.
Waiting for acknowledgement.
LISTEN The socket is listening for incoming connections.
Such sockets are not included in the output unless you
specify the --listening
(-l) or --all (-a) option.
CLOSING
Both sockets are shut down but we still don't have all our
data sent.
UNKNOWN
The state of the socket is unknown.有关 ss 和 netstat 命令之间的用法差异,请查看 Linux 上的 netstat 与 ss 使用指南。
# netstat -nat | awk '{print $6}' | sort | uniq -c | sort -r
8959 CLOSE_WAIT
887 FIN_WAIT2
6 SYN_RECV
5597 TIME_WAIT
472 ESTABLISHED
24 LISTEN
1 SYN_SENT
1 Foreign
1 FIN_WAIT1
1 established)
183 LAST_ACK要了解命令中使用的选项,请阅读 Linux 上的 netstat 与 ss 使用指南。
netstat -apn | grep CLOSE_WAIT | awk '{ print $7 }' | sort | uniq -c | sort -nr如果要将输出限制为具有 CLOSE_WAIT TCP 连接状态的前 10 个进程,请使用 head
# netstat -apn | grep CLOSE_WAIT | awk '{ print $7 }' | sort | uniq -c | sort -nr | head -n 10
3856 8166/jsvc.exec
1783 15643/jsvc.exec
1313 26749/jsvc.exec
1203 11450/jsvc.exec
563 22495/jsvc.exec
270 6698/jsvc.exec
229 22625/jsvc.exec
9 9729/jsvc.exec
2 32038/httpd
2 29352/httpd这表明 ID 为 8166 的进程有 3856 个 CLOSE_WAIT 连接状态。
如果您的 TCP 连接不足或正在进行故障排除,
# ps 8166
PID TTY STAT TIME COMMAND
8166 ? Sl 242:29 jsvc.exec -debug -pidfile /var/run/myapp.pid myapp.jar我制作了一个简单的 bash 脚本,它使用命令 netstat 来识别 TCP 连接状态的计数以及处于 CLOSE_WAIT 状态的进程。
#!/bin/bash
# Script to print Linux TCP connections using netstat
# Github: https://github.com/jmutai
#
# vvvv vvvv-- the code from above
RED='\033[0;31m'
NC='\033[0m' # No Color
echo ""
echo -en "${RED} ALL TCP Connections Count: ${NC}\n"
netstat -nat | awk '{print $6}' | sort | uniq -c | sort -r
echo ""
echo -en "${RED} Top CLOSE_WAIT state TCP Connections: ${NC}\n"
netstat -apn | grep CLOSE_WAIT | awk '{ print $7 }' | sort | uniq -c | sort -nr | head -n 10示例输出:
谢谢你的时间。

