实用脚本能批量测试网站响应时间?

wen 实用脚本 2

本文目录导读:

实用脚本能批量测试网站响应时间?

  1. 方案一:Bash + Curl 脚本 (最快最简单,适合快速巡检)
  2. 方案二:Python + Requests + 多线程 (功能最全,支持并发,输出详细统计)
  3. 方案三:专业版 - 使用 wrk 工具 (最准,用于性能/压力测试)
  4. 总结建议

这是一个非常实用的需求,对于批量测试网站响应时间,我们可以使用多种脚本实现,从简单的 bash + curl,到功能更强大的 Python + requestsaiohttp,再到专业的压测工具 wrk / ab

以下为你提供3个最实用、最常用的脚本方案,覆盖不同场景(简单测试、详细分析、高并发模拟)。


Bash + Curl 脚本 (最快最简单,适合快速巡检)

适用场景: Linux/Mac 环境,只想看每个站点通不通、快不快,无需安装额外依赖。

脚本 (check_response.sh)

#!/bin/bash
# 定义要测试的网址列表,每行一个
# --- 在这里修改你的网站列表 ---
URLS=(
    "https://www.google.com"
    "https://www.github.com"
    "https://www.baidu.com"
    "https://www.example.com" # 这个可能会超时或失败,用于演示
)
# ---------------------------
# 设置超时时间(秒)
TIMEOUT=10
echo "========================================"
echo "开始批量测试网站响应时间 (超时: ${TIMEOUT}s)"
echo "========================================"
for url in "${URLS[@]}"; do
    echo -n "正在测试: $url ... "
    # 使用 curl 获取响应时间
    # -o /dev/null 丢弃正文
    # -s 静默模式
    # -w "%{time_total}" 输出总耗时(秒)
    # --connect-timeout 连接超时
    # --max-time 最大总时间
    result=$(curl -o /dev/null -s -w "%{http_code} %{time_total}" \
                --connect-timeout $TIMEOUT \
                --max-time $((TIMEOUT + 2)) \
                "$url" 2>&1)
    # 检查 curl 是否成功
    if [ $? -eq 0 ]; then
        # 解析结果(状态码 总时间)
        http_code=$(echo "$result" | awk '{print $1}')
        response_time=$(echo "$result" | awk '{print $2}')
        # 将秒转换为毫秒
        response_time_ms=$(echo "$response_time * 1000" | bc 2>/dev/null || echo "N/A")
        # 判断状态码是否正常 (2xx 或 3xx)
        if [[ "$http_code" -ge 200 && "$http_code" -lt 400 ]]; then
            echo -e "\e[32mOK\e[0m (状态: $http_code, 耗时: ${response_time_ms}ms)"
        else
            echo -e "\e[33mWARNING\e[0m (状态: $http_code, 耗时: ${response_time_ms}ms)"
        fi
    else
        echo -e "\e[31mFAILED\e[0m (错误: $result)"
    fi
done
echo "========================================"
echo "测试完成"
echo "========================================"

如何使用:

  1. 将脚本保存为 check_response.sh
  2. 修改脚本中的 URLS 数组,换成你自己的网站列表。
  3. 赋予执行权限:chmod +x check_response.sh
  4. 运行:bash check_response.sh

输出示例:

========================================
开始批量测试网站响应时间 (超时: 10s)
========================================
正在测试: https://www.google.com ... OK (状态: 200, 耗时: 152ms)
正在测试: https://www.github.com ... OK (状态: 200, 耗时: 89ms)
正在测试: https://www.baidu.com ... OK (状态: 200, 耗时: 35ms)
正在测试: https://www.example.com ... WARNING (状态: 503, 耗时: 500ms)
========================================
测试完成
========================================

Python + Requests + 多线程 (功能最全,支持并发,输出详细统计)

适用场景: 需要更细腻的控制,比如统计最大/最小/平均时间,可能需要登录或携带Header,或者需要支持并发测试。

脚本 (check_response.py)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import statistics
# --- 配置 ---
URLS = [
    "https://www.google.com",
    "https://www.github.com",
    "https://www.baidu.com",
    "https://www.example.com"
]
TIMEOUT = 10  # 单次请求超时时间(秒)
NUM_THREADS = 5  # 并发线程数量
# ----------
def test_single_url(url, timeout):
    """测试单个URL的响应时间"""
    result = {
        "url": url,
        "status_code": None,
        "response_time_ms": None,
        "error": None
    }
    try:
        # 记录开始时间
        start_time = time.perf_counter()
        # 发送GET请求,不验证SSL(可改为verify=True)
        response = requests.get(url, timeout=timeout, verify=False, allow_redirects=True)
        # 计算耗时(毫秒)
        elapsed_ms = (time.perf_counter() - start_time) * 1000
        result["status_code"] = response.status_code
        result["response_time_ms"] = round(elapsed_ms, 2)
    except requests.exceptions.Timeout:
        result["error"] = f"Timeout (>{timeout}s)"
    except requests.exceptions.ConnectionError as e:
        result["error"] = f"Connection Error: {e}"
    except Exception as e:
        result["error"] = f"Unexpected Error: {e}"
    return result
def main():
    print("=" * 50)
    print(f"批量测试网站响应时间 (共 {len(URLS)} 个目标, 并发 {NUM_THREADS} 线程)")
    print("=" * 50)
    results = []
    # 使用线程池并发执行
    with ThreadPoolExecutor(max_workers=NUM_THREADS) as executor:
        # 提交所有任务
        future_to_url = {executor.submit(test_single_url, url, TIMEOUT): url for url in URLS}
        # 收集完成的结果
        for future in as_completed(future_to_url):
            url = future_to_url[future]
            try:
                result = future.result()
                results.append(result)
                # 实时打印结果
                if result["error"]:
                    print(f"  ❌ {url}: {result['error']}")
                else:
                    status = "OK" if result["status_code"] < 400 else "WARNING"
                    print(f"  {status:7s} | {url:40s} | Status: {result['status_code']} | Time: {result['response_time_ms']:7.2f}ms")
            except Exception as e:
                print(f"  ❌ {url}: Exception - {e}")
    # 输出汇总统计
    print("\n" + "=" * 50)
    print("汇总统计 (仅统计成功请求的响应时间)")
    print("=" * 50)
    successful_times = [r["response_time_ms"] for r in results if r["error"] is None and r["response_time_ms"] is not None]
    failed_count = sum(1 for r in results if r["error"] is not None)
    print(f"总目标数:      {len(URLS)}")
    print(f"成功数:        {len(successful_times)}")
    print(f"失败数:        {failed_count}")
    if successful_times:
        print(f"平均响应时间:  {statistics.mean(successful_times):.2f}ms")
        print(f"最大响应时间:  {max(successful_times):.2f}ms")
        print(f"最小响应时间:  {min(successful_times):.2f}ms")
        # 计算标准差,反应波动情况
        if len(successful_times) > 1:
            print(f"标准差:        {statistics.stdev(successful_times):.2f}ms")
    print("=" * 50)
if __name__ == "__main__":
    # 忽略 SSL 警告(因为 verify=False)
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    main()

如何使用:

  1. 确保安装了 requests 库:pip install requests
  2. 修改脚本中的 URLS 列表。
  3. 运行:python3 check_response.py

输出示例:

==================================================
批量测试网站响应时间 (共 4 个目标, 并发 5 线程)
==================================================
  OK      | https://www.baidu.com                    | Status: 200 | Time:  35.12ms
  OK      | https://www.github.com                   | Status: 200 | Time:  88.56ms
  OK      | https://www.google.com                   | Status: 200 | Time: 152.34ms
  ❌      | https://www.example.com                  | Connection Error: ...
==================================================
汇总统计 (仅统计成功请求的响应时间)
==================================================
总目标数:      4
成功数:        3
失败数:        1
平均响应时间:  91.67ms
最大响应时间:  152.34ms
最小响应时间:  35.12ms
标准差:        58.63ms
==================================================

专业版 - 使用 wrk 工具 (最准,用于性能/压力测试)

适用场景: 不满足于测一次,需要模拟多用户、高并发、持续压力,看服务器的性能极限。

安装:

  • Mac: brew install wrk
  • Linux (Ubuntu/Debian): 可能需要编译,或使用 apt install wrk (版本可能较旧),推荐从 GitHub Releases 下载。
  • Windows: 使用 WSL。

使用方法 (批量测试的脚本思路):

wrk 本身不支持直接读取文件里的URL列表,你需要写一个简单的循环脚本。

脚本 (wrk_bench.sh)

#!/bin/bash
URLS=(
    "https://www.google.com"
    "https://www.github.com"
    "https://www.baidu.com"
)
# 并发连接数
CONNECTIONS=10
# 测试持续时间(秒)
DURATION=5
echo "使用 wrk 进行负载测试..."
for url in "${URLS[@]}"; do
    echo ""
    echo "=============================================="
    echo "正在测试: $url"
    echo "参数: 并发=$CONNECTIONS, 持续时间=${DURATION}s"
    echo "=============================================="
    wrk -t$CONNECTIONS -c$CONNECTIONS -d${DURATION}s --timeout 5s "$url"
done

运行: bash wrk_bench.sh

输出示例 (wrk 的标准输出):

Running 5s test @ https://www.google.com
  10 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   156.80ms  123.45ms 1.23s    85.67%
    Req/Sec     6.45      3.21    16.00     70.23%
  32 requests in 5.00s, 45.27KB read
  Socket errors: connect 0, read 0, timeout 0, write 0
Requests/sec:      6.40
Transfer/sec:      9.05KB

(这里的数据单位默认是秒和字节,可以加 --latency 看详细延迟分布)


总结建议

场景 推荐方案 优点 缺点
快速巡检 (5个以下网站) 方案一 Bash 无依赖,代码短,适合运维 功能弱,无并发
详细分析 (几十个网站,需统计) 方案二 Python 功能强大,可并发,易扩展 需要 Python 环境
性能/压力测试 (要测极限) 方案三 wrk 专业工具,数据准确,支持高并发 安装稍复杂,只测单一目标

建议: 日常监控用 方案一方案二;做系统优化或上线前压测用 方案三 (wrk)Apache Bench (ab)

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