2026年运维自动化实战:提升千倍效率的Shell与Python脚本分享

在2026年的今天,随着云原生架构与微服务的深度普及,运维团队所面临的管理规模呈指数级增长。传统的人工巡检、手动清理与逐台登录的操作模式早已无法满足业务高可用的要求。自动化不仅是运维的提效工具,更是保障系统稳定性的核心基石。本文将结合当前主流的运维场景,分享三款在2026年依然极其硬核且实用的Shell与Python自动化脚本,帮助大家从繁琐的重复劳动中解放出来。

一、 Shell脚本:批量节点健康巡检与日志智能归档

在大规模集群中,每日的健康巡检与日志清理是必修课。以下Shell脚本实现了对多台服务器的并发巡检(CPU/内存/磁盘利用率),并自动归档压缩超过7天的旧日志,最后通过API将异常结果推送到运维群。


#!/bin/bash
# 2026年运维巡检与日志归档脚本

# 定义服务器列表文件(格式:IP 用户名 密码/密钥路径)
SERVER_LIST="/opt/scripts/servers.ini"
REPORT_FILE="/var/log/ops_report_$(date +%Y%m%d).txt"
ALERT_WEBHOOK="https://your-webhook-url/2026/api"

# 巡检与清理函数
check_and_clean() {
    local ip=$1
    local user=$2
    local auth=$3
    
    # 获取系统负载与磁盘信息
    ssh -i $auth $user@$ip "
        CPU_LOAD=\$(top -bn1 | grep 'Cpu(s)' | awk '{print \$2 + \$4}');
        MEM_USAGE=\$(free -m | awk 'NR==2{printf \"%.2f\", \$3/\$2*100}');
        DISK_USAGE=\$(df -h / | awk 'NR==2{print \$5}' | sed 's/%//g');
        
        echo \"节点: $ip | CPU: \${CPU_LOAD}% | 内存: \${MEM_USAGE}% | 磁盘: \${DISK_USAGE}%\";
        
        # 日志归档:查找/var/log下修改时间超过7天的.log文件并压缩
        find /var/log -name '*.log' -mtime +7 -type f -exec gzip {} \;
        
        # 磁盘告警阈值设为85%
        if [ \${DISK_USAGE%.*} -gt 85 ]; then
            echo \"[ALERT] $ip 磁盘使用率超过85%!\"
        fi
    " >> $REPORT_FILE
}

# 并发执行巡检
while read ip user auth; do
    check_and_clean $ip $user auth &
    # 控制并发数,避免SSH连接耗尽
    if (( $(jobs -r | wc -l) >= 20 )); then
        wait -n
    fi
done < $SERVER_LIST

wait
echo "2026-$(date +%Y-%m-%d) 巡检完成,报告已生成: $REPORT_FILE"

# 检查是否有告警并推送
if grep -q '\[ALERT\]' $REPORT_FILE; then
    ALERT_MSG=$(grep '\[ALERT\]' $REPORT_FILE)
    curl -s -X POST $ALERT_WEBHOOK -H 'Content-Type: application/json' \
         -d "{\"content\": \"⚠️ 2026巡检告警: ${ALERT_MSG}\"}"
fi

核心解析: 该脚本利用后台执行 &wait -n 实现了轻量级的并发控制,极大缩短了百台节点的巡检耗时;同时将巡检与日志归档结合,避免了磁盘写满引发的系统卡死故障。

二、 Python脚本:智能磁盘空间监控与冷热数据分离

Shell脚本虽然轻量,但在处理复杂数据结构(如JSON)和跨平台兼容时,Python是更优的选择。2026年,多数企业已采用对象存储(OSS/S3)作为冷数据池。以下Python脚本实现了本地磁盘监控,并在达到高危水位时,自动将30天前未访问的冷数据迁移至云端。


#!/usr/bin/env python3
# 2026年智能冷热数据分离脚本

import os
import shutil
import boto3
import time
from pathlib import Path

# 配置参数
MONITOR_DIR = "/data/app_logs"
CLOUD_BUCKET = "s3://ops-cold-storage-2026"
THRESHOLD_PERCENT = 90  # 磁盘使用率触发阈值
COLD_FILE_DAYS = 30     # 超过30天未访问即视为冷数据

def get_disk_usage(path):
    stat = os.statvfs(path)
    total = stat.f_blocks * stat.f_frsize
    used = (stat.f_blocks - stat.f_bfree) * stat.f_frsize
    return (used / total) * 100

def migrate_cold_data():
    s3_client = boto3.client('s3')
    now = time.time()
    cold_threshold = now - (COLD_FILE_DAYS * 86400)

    for root, _, files in os.walk(MONITOR_DIR):
        for f in files:
            file_path = Path(root) / f
            # 获取文件最后访问时间
            if file_path.stat().st_atime < cold_threshold:
                try:
                    # 上传至S3
                    s3_key = f"cold-data-2026/{file_path.relative_to(MONITOR_DIR)}"
                    s3_client.upload_file(str(file_path), CLOUD_BUCKET.split('/')[-1], s3_key)
                    # 上传成功后删除本地文件并创建软链接占位
                    file_path.unlink()
                    file_path.symlink_to(f"{CLOUD_BUCKET}/{s3_key}")
                    print(f"[Info] 已迁移冷数据: {file_path} -> {s3_key}")
                except Exception as e:
                    print(f"[Error] 迁移失败 {file_path}: {e}")

if __name__ == "__main__":
    usage = get_disk_usage(MONITOR_DIR)
    if usage > THRESHOLD_PERCENT:
        print(f"[Warning] 磁盘使用率达 {usage:.2f}%,超过阈值 {THRESHOLD_PERCENT}%,启动冷热分离...")
        migrate_cold_data()
    else:
        print(f"[OK] 当前磁盘使用率 {usage:.2f}%,状态健康。")

核心解析: 脚本不仅解决了磁盘告警问题,更引入了“冷热分离”的数据生命周期管理思想。通过上传冷数据至S3并在本地保留软链接,对上层应用实现透明无感的存储降本,这在2026年的FinOps(云财务运营)体系中极具价值。

三、 Python脚本:HTTPS证书到期自动巡检

在安全合规要求极其严格的2026年,SSL证书过期导致的业务中断依然是运维的重大失误。此脚本可定期扫描业务域名,在证书到期前14天触发告警。


#!/usr/bin/env python3
# 2026年SSL证书到期预警脚本

import ssl
import socket
from datetime import datetime
import requests

DOMAINS = ["api.company.com", "portal.company.com", "pay.company.com"]
ALERT_DAYS = 14
WEBHOOK_URL = "https://im-webhook-2026/notify"

def check_ssl_expiry(domain, port=443):
    context = ssl.create_default_context()
    conn = context.wrap_socket(socket.socket(), server_hostname=domain)
    conn.settimeout(5.0)
    
    conn.connect((domain, port))
    cert = conn.getpeercert()
    expiry_date = datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y %Z")
    remaining_days = (expiry_date - datetime.now()).days
    conn.close()
    
    return remaining_days, expiry_date

if __name__ == "__main__":
    for domain in DOMAINS:
        try:
            days_left, exp_date = check_ssl_expiry(domain)
            if days_left <= ALERT_DAYS:
                msg = f"