如何编写批量巡检云主机状态

wen 实用脚本 35

本文目录导读:

如何编写批量巡检云主机状态

  1. 配置认证信息
  2. 每天凌晨2点执行巡检

我来介绍几种批量巡检云主机状态的方法,主要针对阿里云、腾讯云、AWS等主流云平台。

使用云厂商CLI工具(推荐)

阿里云 CLI 批量巡检

#!/bin/bash
# aliyun_health_check.sh
# 获取所有地域
REGIONS=$(aliyun ecs DescribeRegions --output json | jq -r '.Regions.Region[].RegionId')
for REGION in $REGIONS; do
    echo "=== 巡检地域: $REGION ==="
    # 获取该地域所有ECS实例
    aliyun ecs DescribeInstances \
        --RegionId $REGION \
        --output json | jq -r '.Instances.Instance[] | [
            .InstanceId,
            .InstanceName,
            .Status,
            .PublicIpAddress.IpAddress[],
            .InnerIpAddress.IpAddress[]
        ] | @tsv'
    # 检查CPU使用率
    aliyun cms DescribeMetricLast \
        --Project acs_ecs_dashboard \
        --Metric cpu_total \
        --Period 300
done

腾讯云 CLI 批量巡检

#!/bin/bash
# tencentcloud_health_check.sh
# 获取所有实例状态
tccli cvm DescribeInstancesStatus \
    --Offset 0 \
    --Limit 100 | jq -r '.InstanceStatusSet[] | [
        .InstanceId,
        .InstanceState
    ] | @tsv'

AWS CLI 批量巡检

#!/bin/bash
# aws_health_check.sh
# 检查所有EC2实例状态
for region in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
    echo "Region: $region"
    aws ec2 describe-instances \
        --region $region \
        --query 'Reservations[].Instances[].[
            InstanceId, 
            State.Name,
            InstanceType,
            PublicIpAddress
        ]' \
        --output table
done

Python脚本批量巡检

#!/usr/bin/env python3
# cloud_health_check.py
import json
import subprocess
from datetime import datetime
class CloudHealthChecker:
    def __init__(self, cloud_provider='aliyun'):
        self.cloud_provider = cloud_provider
    def check_aliyun_instances(self):
        """巡检阿里云ECS实例"""
        regions_cmd = "aliyun ecs DescribeRegions --output json"
        regions_output = subprocess.check_output(regions_cmd, shell=True)
        regions = json.loads(regions_output)['Regions']['Region']
        health_report = []
        for region in regions:
            region_id = region['RegionId']
            # 获取实例列表
            cmd = f"aliyun ecs DescribeInstances --RegionId {region_id} --output json"
            output = subprocess.check_output(cmd, shell=True)
            instances = json.loads(output)['Instances']['Instance']
            for instance in instances:
                health_info = {
                    'instance_id': instance['InstanceId'],
                    'name': instance.get('InstanceName', 'N/A'),
                    'status': instance['Status'],
                    'region': region_id,
                    'check_time': datetime.now().isoformat()
                }
                # 检查健康状态
                if instance['Status'] == 'Running':
                    # 检查CPU使用率
                    cpu_cmd = f"""aliyun cms DescribeMetricLast \
                        --Project acs_ecs_dashboard \
                        --Metric cpu_total \
                        --Period 300 \
                        --Dimensions "[{{\\\"instanceId\\\":\\\"{instance['InstanceId']}\\\"}}]" """
                    try:
                        cpu_output = subprocess.check_output(cpu_cmd, shell=True)
                        cpu_data = json.loads(cpu_output)
                        if 'Datapoints' in cpu_data:
                            health_info['cpu_usage'] = cpu_data['Datapoints'][-1]['Average']
                    except:
                        health_info['cpu_usage'] = 'N/A'
                health_report.append(health_info)
        return health_report
    def generate_report(self, data):
        """生成巡检报告"""
        print(f"\n{'='*60}")
        print(f"云主机健康巡检报告 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"{'='*60}")
        total = len(data)
        running = sum(1 for i in data if i['status'] == 'Running')
        stopped = sum(1 for i in data if i['status'] == 'Stopped')
        print(f"\n统计信息:")
        print(f"  总实例数: {total}")
        print(f"  运行中: {running}")
        print(f"  已停止: {stopped}")
        print(f"\n实例详情:")
        print(f"{'InstanceId':<20} {'Name':<20} {'Status':<10} {'Region':<15}")
        print("-"*65)
        for instance in data:
            print(f"{instance['instance_id']:<20} "
                  f"{instance['name'][:20]:<20} "
                  f"{instance['status']:<10} "
                  f"{instance['region']:<15}")
        # 保存报告
        report_file = f"health_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        print(f"\n报告已保存至: {report_file}")
if __name__ == "__main__":
    checker = CloudHealthChecker('aliyun')
    report = checker.check_aliyun_instances()
    checker.generate_report(report)

Ansible自动化巡检

---
# ansible_health_check.yml
- name: 云主机健康巡检
  hosts: cloud_instances
  gather_facts: yes
  vars:
    check_time: "{{ ansible_date_time.iso8601 }}"
  tasks:
    - name: 检查系统资源使用
      block:
        - name: CPU使用率
          shell: |
            top -bn1 | grep "Cpu(s)" | \
            awk '{print "CPU_Usage: " $2 + $4 "%"}'
          register: cpu_usage
        - name: 内存使用率
          shell: |
            free | grep Mem | \
            awk '{printf "RAM_Usage: %.2f%%", $3/$2 * 100}'
          register: mem_usage
        - name: 磁盘使用率
          shell: |
            df -h / | awk 'NR==2 {print "Disk_Usage: " $5}'
          register: disk_usage
        - name: 系统运行时间
          shell: |
            uptime
          register: uptime_info
        - name: 关键服务检查
          shell: |
            systemctl is-active --quiet sshd && echo "SSH: Running" || echo "SSH: Stopped"
            systemctl is-active --quiet nginx && echo "Nginx: Running" || echo "Nginx: Stopped"
          register: service_status
          ignore_errors: yes
    - name: 生成巡检报告
      template:
        src: health_report.j2
        dest: "/tmp/health_{{ inventory_hostname }}_{{ check_time }}.txt"
      delegate_to: localhost
- name: 汇总所有主机报告
  hosts: localhost
  tasks:
    - name: 合并报告
      assemble:
        src: /tmp/
        dest: "/tmp/health_report_{{ ansible_date_time.date }}.txt"
        delimiter: "---"
      when: false  # 需要时启用

完整的巡检脚本示例

#!/bin/bash
# comprehensive_cloud_check.sh
echo "========================================"
echo "云主机综合巡检脚本"
echo "开始时间: $(date)"
echo "========================================"
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# 配置文件
CONFIG_FILE="cloud_config.ini"
REPORT_DIR="./reports"
mkdir -p $REPORT_DIR
# 加载配置
load_config() {
    if [ -f "$CONFIG_FILE" ]; then
        source $CONFIG_FILE
    else
        echo "配置文件不存在,使用默认配置"
        CLOUD_PROVIDER="aliyun"
        REGIONS="cn-hangzhou,cn-beijing"
        CHECK_INTERVAL=300
    fi
}
# 巡检单个实例
check_instance() {
    local instance_id=$1
    local region=$2
    echo -e "\n${YELLOW}检查实例: $instance_id${NC}"
    # 获取实例状态
    STATUS=$(aliyun ecs DescribeInstanceAttribute \
        --InstanceId $instance_id \
        --RegionId $region \
        --output json | jq -r '.Status')
    # 检查健康状态
    if [ "$STATUS" == "Running" ]; then
        echo -e "${GREEN}✓ 实例状态: Running${NC}"
        # 获取监控数据
        local cpu_output=$(aliyun cms DescribeMetricLast \
            --Project acs_ecs_dashboard \
            --Metric cpu_total \
            --Period 300 \
            --Dimensions "[{\"instanceId\":\"$instance_id\"}]" 2>/dev/null)
        local mem_output=$(aliyun cms DescribeMetricLast \
            --Project acs_ecs_dashboard \
            --Metric memory_usedutilization \
            --Period 300 \
            --Dimensions "[{\"instanceId\":\"$instance_id\"}]" 2>/dev/null)
        # 解析CPU使用率
        if [ -n "$cpu_output" ]; then
            local cpu_usage=$(echo $cpu_output | jq -r '.Datapoints[-1].Average // "N/A"')
            echo "CPU使用率: ${cpu_usage}%"
            if (( $(echo "$cpu_usage > 80" | bc -l) )); then
                echo -e "${RED}⚠ CPU使用率过高${NC}"
            fi
        fi
        # 解析内存使用率
        if [ -n "$mem_output" ]; then
            local mem_usage=$(echo $mem_output | jq -r '.Datapoints[-1].Average // "N/A"')
            echo "内存使用率: ${mem_usage}%"
            if (( $(echo "$mem_usage > 80" | bc -l) )); then
                echo -e "${RED}⚠ 内存使用率过高${NC}"
            fi
        fi
    else
        echo -e "${YELLOW}⚠ 实例状态: $STATUS${NC}"
    fi
    # 记录结果
    echo "$instance_id|$region|$STATUS|$(date +%Y-%m-%d_%H:%M:%S)" >> "$REPORT_DIR/health_$(date +%Y%m%d).log"
}
# 批量巡检
batch_check() {
    local regions=$1
    IFS=',' read -ra REGION_ARRAY <<< "$regions"
    for region in "${REGION_ARRAY[@]}"; do
        echo -e "\n${GREEN}巡检地域: $region${NC}"
        # 获取该地域所有实例
        aliyun ecs DescribeInstances \
            --RegionId $region \
            --output json | jq -r '.Instances.Instance[].InstanceId' | while read instance_id; do
            check_instance $instance_id $region
        done
    done
}
# 生成HTML报告
generate_html_report() {
    local report_date=$(date +%Y%m%d)
    local log_file="$REPORT_DIR/health_${report_date}.log"
    local html_file="$REPORT_DIR/report_${report_date}.html"
    # 统计信息
    local total=$(wc -l < $log_file)
    local running=$(grep -c "Running" $log_file)
    local stopped=$(grep -c "Stopped" $log_file)
    cat > $html_file <<EOF
<!DOCTYPE html>
<html>
<head>云主机巡检报告</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h1 { color: #333; }
        .summary { background: #f5f5f5; padding: 15px; border-radius: 5px; }
        .running { color: green; }
        .stopped { color: red; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #4CAF50; color: white; }
    </style>
</head>
<body>
    <h1>云主机健康巡检报告</h1>
    <p>生成时间: $(date '+%Y-%m-%d %H:%M:%S')</p>
    <div class="summary">
        <h2>统计概览</h2>
        <p>总实例数: $total</p>
        <p>运行中: <span class="running">$running</span></p>
        <p>已停止: <span class="stopped">$stopped</span></p>
    </div>
    <h2>实例详情</h2>
    <table>
        <tr>
            <th>实例ID</th>
            <th>地域</th>
            <th>状态</th>
            <th>检查时间</th>
        </tr>
EOF
    while IFS='|' read -r id region status time; do
        local status_class=""
        [ "$status" == "Running" ] && status_class="running" || status_class="stopped"
        cat >> $html_file <<EOF
        <tr>
            <td>$id</td>
            <td>$region</td>
            <td class="$status_class">$status</td>
            <td>$time</td>
        </tr>
EOF
    done < $log_file
    echo "</table></body></html>" >> $html_file
    echo -e "${GREEN}HTML报告已生成: $html_file${NC}"
}
# 主程序
main() {
    load_config
    echo -e "${GREEN}开始批量巡检...${NC}"
    batch_check $REGIONS
    echo -e "\n${GREEN}生成报告...${NC}"
    generate_html_report
    echo -e "\n${GREEN}巡检完成!${NC}"
}
main "$@"

使用方法

  1. 配置云厂商CLI
    # 安装CLI工具
    pip install aliyun-cli
    # 或
    brew install awscli

配置认证信息

aliyun configure

aws configure


2. **运行巡检脚本**
```bash
# 直接运行
bash comprehensive_cloud_check.sh
# Python脚本
python3 cloud_health_check.py
# Ansible
ansible-playbook -i inventory ansible_health_check.yml
  1. 设置定时任务
    crontab -e

每天凌晨2点执行巡检

0 2 * /path/to/cloud_check.sh


这些脚本可以根据实际需求进行定制,添加更多检查项如磁盘IO、网络延迟、安全组规则等。

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