可锐资源网

技术资源分享平台,提供编程学习、网站建设、脚本开发教程

linux自动化巡检脚本集

以下是一个自动化巡检脚本集的制作方案,包含常见系统检查项和可扩展框架,使用Python和Shell脚本实现:

#!/usr/bin/env python3
# system_inspector.py

import os
import sys
import subprocess
import psutil
import datetime
import socket

class SystemInspector:
    def __init__(self):
        self.report = []
        self.log_file = "/var/log/system_inspector.log"
        
    def log(self, message, level="INFO"):
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] [{level}] {message}"
        self.report.append(log_entry)
        
    def check_cpu(self):
        try:
            usage = psutil.cpu_percent(interval=1)
            load_avg = os.getloadavg()
            self.log(f"CPU Usage: {usage}% | Load Average: {load_avg}")
            if usage > 90:
                self.log("CPU Warning: Usage over 90%!", "WARNING")
        except Exception as e:
            self.log(f"CPU Check Error: {str(e)}", "ERROR")

    def check_memory(self):
        try:
            mem = psutil.virtual_memory()
            self.log(f"Memory Usage: {mem.percent}% | Available: {mem.available/1024/1024:.2f} MB")
            if mem.percent > 90:
                self.log("Memory Warning: Usage over 90%!", "WARNING")
        except Exception as e:
            self.log(f"Memory Check Error: {str(e)}", "ERROR")

    def check_disk(self):
        try:
            disks = []
            for part in psutil.disk_partitions():
                usage = psutil.disk_usage(part.mountpoint)
                disks.append(f"{part.mountpoint} {usage.percent}%")
                if usage.percent > 90:
                    self.log(f"Disk Warning: {part.mountpoint} over 90%!", "WARNING")
            self.log("Disk Usage: " + " | ".join(disks))
        except Exception as e:
            self.log(f"Disk Check Error: {str(e)}", "ERROR")

    def check_services(self):
        services = ["nginx", "mysql", "redis"]
        try:
            for service in services:
                result = subprocess.run(
                    ["systemctl", "is-active", service],
                    capture_output=True,
                    text=True
                )
                status = result.stdout.strip()
                self.log(f"Service {service}: {status}")
                if status != "active":
                    self.log(f"Service {service} is not active!", "WARNING")
        except Exception as e:
            self.log(f"Service Check Error: {str(e)}", "ERROR")

    def generate_report(self):
        with open(self.log_file, "a") as f:
            f.write("\n".join(self.report) + "\n\n")
        print(f"Inspection completed. Report saved to {self.log_file}")

if __name__ == "__main__":
    inspector = SystemInspector()
    inspector.log("=== Starting System Inspection ===")
    inspector.check_cpu()
    inspector.check_memory()
    inspector.check_disk()
    inspector.check_services()
    inspector.generate_report()

配套Shell脚本(用于基础检查):

#!/bin/bash
# basic_check.sh

# 系统基本信息
echo "===== System Info ====="
echo "Hostname: $(hostname)"
echo "Uptime: $(uptime)"
echo "Kernel: $(uname -r)"

# 内存检查
echo -e "\n===== Memory Usage ====="
free -h

# 磁盘检查
echo -e "\n===== Disk Usage ====="
df -h | grep -v tmpfs

# 进程检查
echo -e "\n===== Top Processes ====="
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -n 6

# 网络检查
echo -e "\n===== Network Connections ====="
netstat -ant | awk '{print $6}' | grep -v '^
| sort | uniq -c # 日志检查(最近错误) echo -e "\n===== Recent Errors =====" journalctl -p 3 -xb --no-pager | tail -n 5

扩展功能建议:

  1. 日志分析增强版(Python):
def analyze_logs(self, log_path="/var/log/syslog", patterns=["error", "fail"]):
    try:
        with open(log_path) as f:
            lines = f.readlines()[-1000:]  # 检查最后1000行
        for pattern in patterns:
            matches = [line for line in lines if pattern.lower() in line.lower()]
            if matches:
                self.log(f"Found {len(matches)} {pattern.upper()} in {log_path}")
                self.log("Last 3 matches:\n" + "\n".join(matches[-3:]), "WARNING")
    except Exception as e:
        self.log(f"Log Analysis Error: {str(e)}", "ERROR")
  1. 网络检测模块(Python):
def check_network(self):
    # 端口检测
    ports = [80, 443, 22]
    for port in ports:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex(('127.0.0.1', port))
        status = "OPEN" if result == 0 else "CLOSED"
        self.log(f"Port {port}: {status}")
        sock.close()
    
    # 网络连通性
    hosts = ["8.8.8.8", "github.com"]
    for host in hosts:
        response = os.system(f"ping -c 1 {host} >/dev/null 2>&1")
        self.log(f"Connectivity to {host}: {'OK' if response == 0 else 'FAIL'}")
  1. 安全基线检查(shell):
#!/bin/bash
# security_check.sh

# SSH配置检查
grep -E "^PermitRootLogin" /etc/ssh/sshd_config | grep -q "no" 
[ $? -eq 0 ] || echo "SSH Warning: PermitRootLogin enabled!"

# 检查SUDO权限变更
find /etc/sudoers -mtime -1 | grep -q sudoers && echo "Sudoers file modified recently!"

# 检查异常用户
echo -e "\n===== User Audit ====="
awk -F: '($3 < 1000) {print $1}' /etc/passwd

使用方式:

  1. 安装依赖:pip3 install psutil
  2. 设置定时任务(每日执行):
# 添加定时任务
(crontab -l 2>/dev/null; echo "0 3 * * * /usr/bin/python3 /path/to/system_inspector.py") | crontab -
(crontab -l 2>/dev/null; echo "0 4 * * * /bin/bash /path/to/basic_check.sh >> /var/log/system_check.log") | crontab -

扩展建议:

  1. 添加邮件/Webhook通知功能
  2. 集成Prometheus/Grafana可视化
  3. 添加自定义阈值配置文件
  4. 实现历史数据对比功能
  5. 增加自动修复功能(谨慎使用)

注意事项:

  1. 根据实际环境调整检查阈值
  2. 定期清理日志文件
  3. 敏感操作需要添加权限验证
  4. 生产环境建议先进行测试
  5. 重要系统建议使用专业监控工具(如Zabbix/Nagios)作为补充
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言