Linux 网站服务器,查看当前连接数命令

在 Linux 网站服务器上,查看当前连接数的命令有多种,根据不同的需求可以使用不同的工具:

1. 查看所有连接数统计

使用 netstat

# 查看所有TCP连接数
netstat -ant | wc -l

# 查看ESTABLISHED状态的连接数
netstat -ant | grep ESTABLISHED | wc -l

# 按状态分类统计
netstat -ant | awk '/^tcp/ {print $6}' | sort | uniq -c

使用 ss(推荐,更快速)

# 查看所有TCP连接数
ss -t | wc -l

# 查看ESTABLISHED状态的连接数
ss -t state established | wc -l

# 按状态分类统计
ss -t -a | awk '{print $2}' | sort | uniq -c

2. 查看HTTP连接数(针对Web服务器)

查看80/443端口连接数

# 查看80端口连接
netstat -ant | grep :80 | wc -l

# 查看443端口连接
netstat -ant | grep :443 | wc -l

# 使用ss查看
ss -t sport = :80 or sport = :443 | wc -l

3. 查看Nginx连接数

查看Nginx状态

# 如果配置了status模块
curl http://localhost/nginx_status

# 或查看Nginx进程信息
ps -ef | grep nginx | wc -l

查看Nginx活动连接数

# 查看Nginx的进程连接数
netstat -ant | grep nginx | wc -l

4. 查看Apache连接数

# 查看Apache连接数
netstat -ant | grep httpd | wc -l

# 或查看Apache进程数
ps -ef | grep httpd | wc -l

5. 实时监控连接数

使用 watch 命令实时监控

# 每2秒刷新一次连接数
watch -n 2 "netstat -ant | grep :80 | wc -l"

# 实时监控各种状态的连接数
watch -n 2 "netstat -ant | awk '/^tcp/ {print \$6}' | sort | uniq -c"

6. 查看IP连接数排名

# 查看连接数最多的前10个IP
netstat -ant | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -n 10

# 使用ss查看
ss -t | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -n 10

7. 综合监控脚本

#!/bin/bash
echo "=== 当前服务器连接数统计 ==="
echo "所有TCP连接数: $(netstat -ant | wc -l)"
echo "ESTABLISHED连接数: $(netstat -ant | grep ESTABLISHED | wc -l)"
echo "HTTP(80)连接数: $(netstat -ant | grep :80 | wc -l)"
echo "HTTPS(443)连接数: $(netstat -ant | grep :443 | wc -l)"
echo ""
echo "=== 连接状态分布 ==="
netstat -ant | awk '/^tcp/ {print $6}' | sort | uniq -c

常用状态说明

  • ESTABLISHED:已建立的连接
  • TIME_WAIT:等待关闭的连接
  • CLOSE_WAIT:远程已关闭,本地未关闭
  • LISTEN:监听状态

推荐使用

对于现代Linux系统,推荐使用 ss 命令替代 netstat,因为 ss 速度更快,显示的信息也更详细。

未经允许不得转载:Song It » Linux 网站服务器,查看当前连接数命令

相关文章

评论 (0)