如何编写网络连通性测试脚本

wen 实用脚本 1

本文目录导读:

如何编写网络连通性测试脚本

  1. PowerShell 脚本(Windows)
  2. Bash 脚本(Linux/Unix)
  3. Python 脚本(跨平台)
  4. 高级功能脚本
  5. 使用方法
  6. 使用建议

PowerShell 脚本(Windows)

基础 Ping 测试

# 简单ping测试
$hosts = @("google.com", "baidu.com", "192.168.1.1")
foreach ($host in $hosts) {
    Write-Host "测试 $host ..." -ForegroundColor Yellow
    $result = Test-Connection -ComputerName $host -Count 3 -Quiet
    if ($result) {
        Write-Host "$host 连通" -ForegroundColor Green
    } else {
        Write-Host "$host 不通" -ForegroundColor Red
    }
}

综合测试脚本

param(
    [string[]]$TargetHosts = @("www.baidu.com", "www.google.com"),
    [int]$PingCount = 4,
    [int]$TimeoutSec = 5
)
function Test-Network {
    param([string]$Host)
    Write-Host "`n[$(Get-Date -Format 'HH:mm:ss')] 测试: $Host" -ForegroundColor Cyan
    # TCP 端口测试
    $tcpResult = Test-NetConnection -ComputerName $Host -Port 80 -WarningAction SilentlyContinue
    if ($tcpResult.TcpTestSucceeded) {
        Write-Host "✓ TCP 80端口连通" -ForegroundColor Green
    } else {
        Write-Host "✗ TCP 80端口不通" -ForegroundColor Red
    }
    # DNS 解析
    try {
        $dnsResult = Resolve-DnsName $Host -ErrorAction Stop
        Write-Host "✓ DNS解析成功: $($dnsResult.IPAddress)" -ForegroundColor Green
    } catch {
        Write-Host "✗ DNS解析失败" -ForegroundColor Red
    }
    # Ping 测试
    $pingResult = Test-Connection -ComputerName $Host -Count $PingCount -ErrorAction SilentlyContinue
    if ($pingResult) {
        $avgTime = ($pingResult | Measure-Object -Property ResponseTime -Average).Average
        Write-Host "✓ Ping平均延迟: $($avgTime)ms" -ForegroundColor Green
    } else {
        Write-Host "✗ Ping失败" -ForegroundColor Red
    }
}
foreach ($host in $TargetHosts) {
    Test-Network -Host $host
}

Bash 脚本(Linux/Unix)

基础连通性测试

#!/bin/bash
# 定义测试主机列表
HOSTS=("8.8.8.8" "google.com" "192.168.1.1" "baidu.com")
PING_COUNT=4
TIMEOUT=5
echo "=== 网络连通性测试开始 $(date) ==="
for host in "${HOSTS[@]}"; do
    echo -e "\n测试: $host"
    # Ping 测试
    if ping -c $PING_COUNT -W $TIMEOUT "$host" > /dev/null 2>&1; then
        avg_time=$(ping -c $PING_COUNT -W $TIMEOUT "$host" | tail -1 | awk -F '/' '{print $5}')
        echo "✓ Ping成功 | 平均延迟: ${avg_time}ms"
    else
        echo "✗ Ping失败"
    fi
    # TCP 端口测试(HTTP)
    if timeout $TIMEOUT bash -c "echo >/dev/tcp/$host/80" 2>/dev/null; then
        echo "✓ TCP 80端口连通"
    else
        echo "✗ TCP 80端口不通"
    fi
    # DNS 解析测试
    if nslookup "$host" > /dev/null 2>&1; then
        ip_address=$(dig +short "$host" | head -1)
        echo "✓ DNS解析成功: ${ip_address:-$host}"
    else
        echo "✗ DNS解析失败"
    fi
done
# 网络接口状态
echo -e "\n=== 网络接口状态 ==="
ip addr show | grep -E "^[0-9]+:|inet "
# 路由信息
echo -e "\n=== 路由信息 ==="
ip route show
echo -e "\n=== 测试完成 $(date) ==="

Python 脚本(跨平台)

#!/usr/bin/env python3
import socket
import subprocess
import platform
import sys
from datetime import datetime
import threading
from queue import Queue
class NetworkTester:
    def __init__(self, hosts, timeout=5):
        self.hosts = hosts
        self.timeout = timeout
        self.results = []
    def ping_test(self, host):
        """Ping 测试"""
        try:
            param = '-n' if platform.system().lower() == 'windows' else '-c'
            cmd = ['ping', param, '4', '-W', str(self.timeout), host]
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=self.timeout)
            return result.returncode == 0
        except:
            return False
    def tcp_test(self, host, port=80):
        """TCP 端口测试"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(self.timeout)
            result = sock.connect_ex((host, port))
            sock.close()
            return result == 0
        except:
            return False
    def dns_test(self, host):
        """DNS 解析测试"""
        try:
            socket.gethostbyname(host)
            return True
        except:
            return False
    def run_test(self, host):
        """执行单个主机的测试"""
        timestamp = datetime.now().strftime('%H:%M:%S')
        print(f"\n[{timestamp}] 测试: {host}")
        print("-" * 50)
        # Ping 测试
        if self.ping_test(host):
            print("✓ Ping 测试通过")
        else:
            print("✗ Ping 测试失败")
        # TCP 测试
        if self.tcp_test(host, 80):
            print("✓ TCP 80端口测试通过")
        else:
            print("✗ TCP 80端口测试失败")
        # DNS 测试
        if self.dns_test(host):
            print("✓ DNS 解析成功")
        else:
            print("✗ DNS 解析失败")
    def run_all(self):
        print(f"=== 网络连通性测试开始 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
        print(f"测试目标: {', '.join(self.hosts)}")
        print("=" * 50)
        for host in self.hosts:
            self.run_test(host)
        print("\n=== 测试完成 ===")
# 使用示例
if __name__ == "__main__":
    hosts = ["8.8.8.8", "www.baidu.com", "www.google.com", "192.168.1.1"]
    tester = NetworkTester(hosts, timeout=5)
    tester.run_all()

高级功能脚本

带日志和告警的测试脚本(Bash)

#!/bin/bash
# 网络监控脚本
LOGFILE="/var/log/network_test.log"
WEBHOOK_URL="https://your-webhook-url"
THRESHOLD_LATENCY=100  # 延迟阈值ms
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOGFILE"
}
send_alert() {
    local message="$1"
    curl -X POST -H "Content-Type: application/json" \
         -d "{\"text\": \"NETWORK ALERT: $message\"}" \
         "$WEBHOOK_URL" 2>/dev/null
}
test_connectivity() {
    local host="$1"
    local result=$(ping -c 3 -W 3 "$host" 2>&1)
    if [ $? -eq 0 ]; then
        local latency=$(echo "$result" | tail -1 | awk -F '/' '{print $5}')
        log "OK: $host latency=${latency}ms"
        # 延迟告警
        if (( $(echo "$latency > $THRESHOLD_LATENCY" | bc -l) )); then
            send_alert "高延迟: $host ${latency}ms"
        fi
    else
        log "FAIL: $host 连接失败"
        send_alert "连接中断: $host"
    fi
}
# 监控主循环
while true; do
    echo "=== 定时检查 $(date) ==="
    for host in "8.8.8.8" "google.com"; do
        test_connectivity "$host"
    done
    sleep 60  # 每分钟检查一次
done

多线程测试(Python)

import concurrent.futures
import time
def test_host(host):
    """并发测试单个主机"""
    start_time = time.time()
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(3)
        result = sock.connect_ex((host, 80))
        sock.close()
        latency = (time.time() - start_time) * 1000
        if result == 0:
            return f"{host}: 成功 ({latency:.1f}ms)"
        else:
            return f"{host}: 失败"
    except:
        return f"{host}: 超时"
def parallel_test(hosts):
    """并行测试多个主机"""
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        results = list(executor.map(test_host, hosts))
    for result in results:
        print(result)
# 使用
hosts = [f"192.168.1.{i}" for i in range(1, 255)]
parallel_test(hosts)

使用方法

一键测试脚本(Bash)

#!/bin/bash
# 自动检测并执行网络测试
echo "==================================="
echo "    网络连通性测试工具"
echo "==================================="
# 检查权限
if [ "$EUID" -ne 0 ]; then 
    echo "请以root权限运行"
    exit 1
fi
# 检测系统类型
OS=$(uname -s)
echo "系统: $OS"
case $OS in
    Linux)
        echo "使用Linux网络工具"
        command -v ping >/dev/null 2>&1 || { echo "需要安装ping工具"; exit 1; }
        ;;
    Darwin)
        echo "使用macOS网络工具"
        ;;
    *)
        echo "未知系统"
        exit 1
        ;;
esac
# 执行测试
bash network_test.sh

使用建议

  1. 选择合适的脚本:根据操作系统和使用场景选择合适的脚本语言
  2. 定时任务:使用 crontab 或计划任务定期执行
  3. 日志记录:保存测试结果到日志文件
  4. 告警通知:配置邮件或消息推送告警
  5. 参数化:允许用户自定义测试参数
  6. 错误处理:添加适当的错误处理和重试机制

这些脚本可以作为基础模板,根据实际需求进行修改和扩展。

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