脚本如何检测负载均衡是否正常

wen 实用脚本 2

本文目录导读:

脚本如何检测负载均衡是否正常

  1. 基础网络连通性检测
  2. 后端节点可用性检测
  3. 请求分发均衡性检测
  4. 综合检测脚本
  5. 高级检测技术
  6. 使用建议
  7. 注意事项

检测负载均衡是否正常,可以从不同层面入手,我为您整理了一份脚本检测的方法指南,涵盖从网络层到应用层的多种检测策略。

基础网络连通性检测

1 端口可达性检测(使用bash + netcat)

#!/bin/bash
# 检测负载均衡器的端口是否正常
LB_HOST="your-lb-domain.com"
LB_PORT=80
nc -zv $LB_HOST $LB_PORT 2>&1 | grep -q "succeeded"
if [ $? -eq 0 ]; then
    echo "✅ 负载均衡器端口可达"
else
    echo "❌ 负载均衡器端口不可达"
fi

2 健康检查端点测试

# health_check.py
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def check_lb_health(url, timeout=5):
    """检测负载均衡健康检查端点"""
    session = requests.Session()
    retry = Retry(total=3, backoff_factor=0.5)
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    try:
        response = session.get(f"{url}/health", timeout=timeout)
        if response.status_code == 200:
            print(f"✅ 健康检查端点正常: {url}")
            return True
        else:
            print(f"❌ 健康检查端点异常,状态码: {response.status_code}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
        return False
check_lb_health("http://your-lb-domain.com")

后端节点可用性检测

1 节点逐一检测

#!/bin/bash
# 后端节点列表
BACKEND_SERVERS=(
    "192.168.1.10:8080"
    "192.168.1.11:8080" 
    "192.168.1.12:8080"
)
echo "===== 后端节点健康检测 ====="
for server in "${BACKEND_SERVERS[@]}"; do
    if curl -s -m 5 "http://$server/" > /dev/null 2>&1; then
        echo "✅ $server 正常"
    else
        echo "❌ $server 异常"
    fi
done

2 全量节点并发检测(Python)

# concurrent_health_check.py
import asyncio
import aiohttp
from typing import List
async def check_node(session, node_url):
    """异步检测单个节点"""
    try:
        async with session.get(f"http://{node_url}/health", timeout=aiohttp.ClientTimeout(total=5)) as resp:
            if resp.status == 200:
                return (node_url, True)
            else:
                return (node_url, False)
    except:
        return (node_url, False)
async def check_all_nodes(nodes: List[str]):
    """并发检测所有后端节点"""
    async with aiohttp.ClientSession() as session:
        tasks = [check_node(session, node) for node in nodes]
        results = await asyncio.gather(*tasks)
        return results
# 使用示例
nodes = ["192.168.1.10:8080", "192.168.1.11:8080", "192.168.1.12:8080"]
results = asyncio.run(check_all_nodes(nodes))
for node, status in results:
    print(f"{'✅' if status else '❌'} {node}")

请求分发均衡性检测

1 利用唯一头部追踪分发

#!/bin/bash
# 检测请求是否被均匀分发到不同后端
for i in {1..100}; do
    response=$(curl -s -H "X-Test-Id: $RANDOM" http://your-lb-domain.com/ | grep "Server-ID" | awk '{print $2}')
    echo "$response" >> server_ids.txt
done
# 统计各服务器接收请求数
echo "===== 请求分发统计 ====="
sort server_ids.txt | uniq -c | sort -nr

2 HTTP响应时间稳定性检测

# response_time_test.py
import time
import statistics
import requests
def test_response_stability(url, num_requests=50):
    """测试负载均衡响应时间稳定性"""
    response_times = []
    for i in range(num_requests):
        start_time = time.time()
        try:
            response = requests.get(url, timeout=10)
            elapsed = time.time() - start_time
            response_times.append(elapsed)
        except:
            response_times.append(None)
    clean_times = [t for t in response_times if t is not None]
    if clean_times:
        avg = statistics.mean(clean_times)
        std = statistics.stdev(clean_times) if len(clean_times) > 1 else 0
        print(f"✅ 平均响应时间: {avg*1000:.2f}ms")
        print(f"✅ 响应时间标准差: {std*1000:.2f}ms")
        print(f"✅ 最大响应时间: {max(clean_times)*1000:.2f}ms")
        print(f"✅ 最小响应时间: {min(clean_times)*1000:.2f}ms")
        if std > avg * 0.5:
            print("⚠️ 响应时间波动较大,可能存在问题")
        else:
            print("✅ 响应时间稳定")
    else:
        print("❌ 所有请求均失败")
test_response_stability("http://your-lb-domain.com/")

综合检测脚本

1 完整的负载均衡健康检测

#!/bin/bash
# comprehensive_lb_check.sh
# 配置
LB_URL="http://your-lb-domain.com"
BACKEND_NODES=(
    "192.168.1.10:8080"
    "192.168.1.11:8080"
    "192.168.1.12:8080"
)
HEALTH_ENDPOINT="/health"
TEST_COUNT=10
# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${YELLOW}===== 负载均衡全面检测 =====${NC}\n"
# 1. 基础连通性检测
echo -e "${YELLOW}[1] 基础连通性检测${NC}"
if curl -s -m 5 "$LB_URL$HEALTH_ENDPOINT" > /dev/null 2>&1; then
    echo -e "${GREEN}✅ 负载均衡器可达${NC}"
else
    echo -e "${RED}❌ 负载均衡器不可达${NC}"
    exit 1
fi
# 2. 后端节点检测
echo -e "\n${YELLOW}[2] 后端节点检测${NC}"
active_count=0
for node in "${BACKEND_NODES[@]}"; do
    if curl -s -m 3 "http://$node$HEALTH_ENDPOINT" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ $node 正常${NC}"
        ((active_count++))
    else
        echo -e "${RED}❌ $node 异常${NC}"
    fi
done
echo -e "在线节点数: $active_count/${#BACKEND_NODES[@]}"
if [ $active_count -eq 0 ]; then
    echo -e "${RED}❌ 没有后端节点可用${NC}"
    exit 1
fi
# 3. 请求分发测试
echo -e "\n${YELLOW}[3] 请求分发测试${NC}"
declare -A distribution
for i in $(seq 1 $TEST_COUNT); do
    response=$(curl -s -w '%{http_code}' -o /dev/null "$LB_URL/")
    distribution[$response]=$((distribution[$response] + 1))
done
echo "状态码分布:"
for code in "${!distribution[@]}"; do
    echo "  $code: ${distribution[$code]}次"
done
if [ ! -z "${distribution[200]}" ]; then
    echo -e "${GREEN}✅ 请求分发正常${NC}"
else
    echo -e "${RED}❌ 所有请求返回非200状态码${NC}"
fi
echo -e "\n${YELLOW}===== 检测完成 =====${NC}"

高级检测技术

1 基于Keepalived状态的检测(Nginx环境)

#!/bin/bash
# 检测Nginx upstream状态
# 需要安装nginx-module-http-upstream-health
UPSTREAM_NAME="backend_cluster"
# 通过nginx status页面获取信息
STATUS_URL="http://127.0.0.1/nginx_status"
if curl -s "$STATUS_URL" | grep -q "$UPSTREAM_NAME"; then
    echo "✅ 后端集群上游服务正常"
    # 检测具体节点状态
    curl -s "$STATUS_URL" | grep "server" | while read line; do
        if echo "$line" | grep -q "up"; then
            echo -e "${GREEN}✅ 节点正常: $line${NC}"
        else
            echo -e "${RED}❌ 节点异常: $line${NC}"
        fi
    done
else
    echo "❌ 无法获取upstream状态"
fi

2 使用Prometheus指标监控

# prometheus_check.py
from prometheus_api_client import PrometheusConnect
import requests
def check_lb_prometheus_metrics(prometheus_url, lb_name):
    """通过Prometheus检测负载均衡健康"""
    prom = PrometheusConnect(url=prometheus_url, disable_ssl=True)
    # 查询后端节点存活数
    query = f'up{{job="{lb_name}"}}'
    result = prom.custom_query(query=query)
    if result:
        alive_nodes = sum(1 for metric in result if metric['value'][1] == '1')
        total_nodes = len(result)
        print(f"在线节点: {alive_nodes}/{total_nodes}")
        if alive_nodes == total_nodes:
            print("✅ 所有节点正常")
        elif alive_nodes >= total_nodes * 0.5:
            print("⚠️ 部分节点异常,但不影响服务")
        else:
            print("❌ 多数节点异常,需要立即处理")
    else:
        print("❌ 无法获取指标数据")

使用建议

  1. 调整超时时间:根据您的网络延迟情况调整timeout参数
  2. 增加重试机制:单次失败不意味着服务不可用,建议增加重试逻辑
  3. 记录日志:将检测结果输出到日志文件,便于后期分析
  4. 设置阈值告警:当检测到异常时,通过邮件、短信等方式通知运维人员
  5. 定期执行:使用cron或定时任务将检测脚本定期执行

注意事项

  • 生产环境中建议使用HTTPS协议进行检测
  • 注意不要对后端造成过大压力,适当控制检测频率
  • 考虑使用专门的监控工具(如Nagios、Zabbix、Grafana + Prometheus)作为补充
  • 对于不同的负载均衡软件(Nginx、HAProxy、AWS ELB等),检测方法可能有所不同

如果您需要针对特定负载均衡解决方案的检测脚本,请提供更多详细信息,我可以为您定制更精准的检测方案。

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