怎么用脚本获取端口连接数

wen 实用脚本 2

本文目录导读:

怎么用脚本获取端口连接数

  1. Linux 系统脚本
  2. Windows 系统脚本
  3. 高级脚本示例
  4. 跨平台脚本(Python)
  5. 输出示例
  6. 使用建议

Linux 系统脚本

使用 netstat 命令

#!/bin/bash
# 获取指定端口连接数(这里以 80 端口为例)
PORT=80
connections=$(netstat -ant | grep ":$PORT " | wc -l)
echo "端口 $PORT 的连接数: $connections"

使用 ss 命令(推荐,更快)

#!/bin/bash
PORT=80
connections=$(ss -ant | grep ":$PORT " | wc -l)
echo "端口 $PORT 的连接数: $connections"

按 IP 统计连接数

#!/bin/bash
PORT=80
echo "端口 $PORT 的连接统计:"
netstat -ant | grep ":$PORT " | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -rn

Windows 系统脚本

PowerShell 版本

# 获取指定端口连接数(以 443 端口为例)
$port = 443
$connections = (netstat -an | Select-String ":$port ").Count
Write-Host "端口 $port 的连接数: $connections"

详细的连接统计

$port = 443
Write-Host "端口 $port 的连接统计:"
netstat -an | Select-String ":$port " | ForEach-Object {
    $line = $_.ToString().Split()
    $state = $line[-1]
    $state
} | Group-Object | Select-Object Count, Name

高级脚本示例

监控多个端口

#!/bin/bash
ports=(80 443 3306 8080)
echo "当前时间: $(date +'%Y-%m-%d %H:%M:%S')"
echo "================================"
for port in "${ports[@]}"; do
    connections=$(ss -ant | grep ":$port " | wc -l)
    echo "端口 $port: $connections 个连接"
done

实时监控脚本

#!/bin/bash
PORT=80
while true; do
    clear
    echo "实时监控端口 $PORT - $(date +'%H:%M:%S')"
    echo "=================================="
    connections=$(ss -ant | grep ":$port " | wc -l)
    echo "当前连接数: $connections"
    # 显示连接状态分布
    echo -e "\n连接状态分布:"
    ss -ant | grep ":$port " | awk '{print $1}' | sort | uniq -c | sort -rn
    sleep 2
done

跨平台脚本(Python)

#!/usr/bin/env python3
import subprocess
import platform
import re
def get_port_connections(port):
    system = platform.system()
    if system == "Windows":
        cmd = f"netstat -an | findstr :{port} "
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        lines = result.stdout.strip().split('\n') if result.stdout else []
        return len(lines)
    else:  # Linux/Mac
        cmd = f"ss -ant | grep ':{port} '"
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        lines = result.stdout.strip().split('\n') if result.stdout else []
        return len(lines)
# 使用示例
port = 80
count = get_port_connections(port)
print(f"端口 {port} 的连接数: {count}")

输出示例

$ ./check_port.sh
当前时间: 2024-01-15 10:30:45
================================
端口 80: 156 个连接
端口 443: 89 个连接
端口 3306: 12 个连接
端口 8080: 0 个连接

使用建议

  1. 权限要求:某些系统需要 root/管理员权限才能查看所有连接
  2. 性能考虑ssnetstat 更快,建议优先使用
  3. 定期监控:可以结合 crontab 或任务计划程序设置定期检查
  4. 异常告警:可以添加阈值判断,超过时发送告警

选择哪种方法取决于你的操作系统和具体需求,Linux 系统推荐使用 ss 命令,Windows 推荐使用 PowerShell。

抱歉,评论功能暂时关闭!