#!/bin/bash

# 检查netstat是否安装
if ! command -v netstat &> /dev/null; then
    echo "netstat未安装，正在尝试安装..."
    # 判断Linux发行版
    if [[ -f /etc/redhat-release ]]; then
        sudo yum install net-tools -y
    elif [[ -f /etc/lsb-release ]]; then
        sudo apt-get update
        sudo apt-get install net-tools -y
    else
        echo "无法识别的Linux发行版，请手动安装net-tools。"
        exit 1
    fi
fi

# TCP连接数
echo "TCP连接数:"
netstat -nat | awk '/^tcp/ {++S[$NF]} END {for(a in S) printf "%-12s %s\n", a, S[a]}'

# UDP连接数
echo "UDP连接数:"
netstat -nau | awk '/^udp/ {++S[$NF]} END {for(a in S) printf "%-12s %s\n", a, S[a]}'
