定时生成系统快照的脚本

wen 实用脚本 1

本文目录导读:

定时生成系统快照的脚本

  1. Linux 系统快照脚本
  2. Windows 系统快照脚本 (PowerShell)
  3. 定时任务配置脚本
  4. 配置文件示例
  5. 使用方法
  6. 高级功能扩展

我来为您提供一个完善的定时系统快照脚本,这个脚本支持Windows和Linux系统。

Linux 系统快照脚本

#!/bin/bash
# Linux系统定时快照脚本
# 配置变量
SNAPSHOT_DIR="/var/backups/system_snapshots"
RETENTION_DAYS=7
LOG_FILE="/var/log/snapshot.log"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
SNAPSHOT_NAME="system_snapshot_${TIMESTAMP}"
# 确保目录存在
mkdir -p "$SNAPSHOT_DIR"
# 日志函数
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}
# 检查是否有root权限
if [[ $EUID -ne 0 ]]; then
    log_message "错误:需要root权限运行此脚本"
    exit 1
}
# 创建快照函数
create_snapshot() {
    log_message "开始创建系统快照..."
    # 创建临时目录
    TEMP_DIR="${SNAPSHOT_DIR}/${SNAPSHOT_NAME}"
    mkdir -p "$TEMP_DIR"
    # 备份关键系统信息
    echo "=== 系统信息 ===" > "${TEMP_DIR}/system_info.txt"
    echo "时间: $(date)" >> "${TEMP_DIR}/system_info.txt"
    uname -a >> "${TEMP_DIR}/system_info.txt"
    echo "" >> "${TEMP_DIR}/system_info.txt"
    echo "=== 系统负载 ===" >> "${TEMP_DIR}/system_info.txt"
    uptime >> "${TEMP_DIR}/system_info.txt"
    echo "" >> "${TEMP_DIR}/system_info.txt"
    echo "=== 内存使用 ===" >> "${TEMP_DIR}/system_info.txt"
    free -h >> "${TEMP_DIR}/system_info.txt"
    echo "" >> "${TEMP_DIR}/system_info.txt"
    echo "=== 磁盘使用 ===" >> "${TEMP_DIR}/system_info.txt"
    df -h >> "${TEMP_DIR}/system_info.txt"
    echo "" >> "${TEMP_DIR}/system_info.txt"
    # 备份系统配置
    cp /etc/passwd "${TEMP_DIR}/etc_passwd.bak"
    cp /etc/group "${TEMP_DIR}/etc_group.bak"
    cp /etc/shadow "${TEMP_DIR}/etc_shadow.bak"
    cp /etc/resolv.conf "${TEMP_DIR}/etc_resolv.conf.bak"
    cp /etc/hosts "${TEMP_DIR}/etc_hosts.bak"
    cp /etc/fstab "${TEMP_DIR}/etc_fstab.bak"
    # 备份分区表
    sfdisk -d /dev/sda > "${TEMP_DIR}/partition_table.bak" 2>/dev/null || true
    # 备份包列表
    dpkg --get-selections > "${TEMP_DIR}/package_list.bak" 2>/dev/null || 
    rpm -qa > "${TEMP_DIR}/package_list.bak" 2>/dev/null || true
    # 备份crontab
    crontab -l > "${TEMP_DIR}/crontab.bak" 2>/dev/null || true
    # 压缩快照
    tar -czf "${SNAPSHOT_DIR}/${SNAPSHOT_NAME}.tar.gz" -C "${SNAPSHOT_DIR}" "$SNAPSHOT_NAME"
    # 删除临时目录
    rm -rf "$TEMP_DIR"
    log_message "快照 ${SNAPSHOT_NAME}.tar.gz 创建成功"
}
# 清理旧快照函数
cleanup_old_snapshots() {
    log_message "清理 ${RETENTION_DAYS} 天前的旧快照..."
    # 找出并删除旧快照
    find "$SNAPSHOT_DIR" -name "*.tar.gz" -mtime +"$RETENTION_DAYS" -exec rm -f {} \;
    # 记录清理结果
    CLEANUP_COUNT=$(find "$SNAPSHOT_DIR" -name "*.tar.gz" -mtime +"$RETENTION_DAYS" | wc -l)
    log_message "清理完成,删除了 $CLEANUP_COUNT 个旧快照"
    # 显示剩余快照
    echo "当前保留的快照:"
    ls -lh "$SNAPSHOT_DIR"/*.tar.gz 2>/dev/null || echo "没有快照文件"
}
# 主函数
main() {
    log_message "系统快照脚本启动"
    # 创建快照
    create_snapshot
    # 清理旧快照
    cleanup_old_snapshots
    log_message "系统快照脚本执行完成"
}
# 执行主函数
main

Windows 系统快照脚本 (PowerShell)

# Windows系统定时快照脚本
# 文件名: create-snapshot.ps1
# 配置参数
$SnapshotDir = "C:\SystemSnapshots"
$RetentionDays = 7
$LogFile = "C:\SystemSnapshots\snapshot.log"
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$SnapshotName = "system_snapshot_$Timestamp"
$SnapshotPath = "$SnapshotDir\$SnapshotName"
# 日志函数
function Write-Log {
    param([string]$Message)
    $LogTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "[$LogTime] $Message" | Out-File -FilePath $LogFile -Append
    Write-Host "[$LogTime] $Message"
}
# 确保目录存在
if (!(Test-Path $SnapshotDir)) {
    New-Item -ItemType Directory -Path $SnapshotDir -Force | Out-Null
    Write-Log "创建快照目录: $SnapshotDir"
}
# 创建系统信息快照
function Create-SystemInfoSnapshot {
    Write-Log "开始收集系统信息..."
    # 创建快照目录
    New-Item -ItemType Directory -Path $SnapshotPath -Force | Out-Null
    # 系统基本信息
    $SystemInfo = @{
        Timestamp = Get-Date
        ComputerName = $env:COMPUTERNAME
        OS = (Get-WmiObject Win32_OperatingSystem).Caption
        Version = (Get-WmiObject Win32_OperatingSystem).Version
        LastBootTime = (Get-WmiObject Win32_OperatingSystem).LastBootUpTime
        Memory = "{0:N2} GB" -f ((Get-WmiObject Win32_ComputerSystem).TotalPhysicalMemory / 1GB)
        CPU = (Get-WmiObject Win32_Processor).Name
    }
    # 保存系统信息
    $SystemInfo | ConvertTo-Json | Out-File "$SnapshotPath\system_info.json"
    # 磁盘信息
    Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID, @{Name="Size(GB)";Expression={$_.Size/1GB}}, @{Name="FreeSpace(GB)";Expression={$_.FreeSpace/1GB}} | 
        ConvertTo-Json | Out-File "$SnapshotPath\disk_info.json"
    # 服务信息
    Get-Service | Select-Object Status, Name, DisplayName | 
        ConvertTo-Csv -NoTypeInformation | Out-File "$SnapshotPath\services.csv"
    # 安装的软件列表
    Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" |
        Select-Object DisplayName, DisplayVersion, Publisher |
        ConvertTo-Csv -NoTypeInformation | Out-File "$SnapshotPath\installed_software.csv"
    # 网络配置
    ipconfig /all | Out-File "$SnapshotPath\network_config.txt"
    # 路由表
    route print | Out-File "$SnapshotPath\routing_table.txt"
    # ARP表
    arp -a | Out-File "$SnapshotPath\arp_table.txt"
    # 计划任务
    Get-ScheduledTask | Select-Object TaskName, State, TaskPath | 
        ConvertTo-Csv -NoTypeInformation | Out-File "$SnapshotPath\scheduled_tasks.csv"
    # 事件日志(最近的关键事件)
    Get-EventLog -LogName "Application" -EntryType Error -Newest 50 |
        Select-Object TimeWritten, Source, EventID, Message |
        ConvertTo-Csv -NoTypeInformation | Out-File "$SnapshotPath\application_errors.csv"
    Get-EventLog -LogName "System" -EntryType Error -Newest 50 |
        Select-Object TimeWritten, Source, EventID, Message |
        ConvertTo-Csv -NoTypeInformation | Out-File "$SnapshotPath\system_errors.csv"
    Write-Log "系统信息收集完成"
}
# 压缩快照
function Compress-Snapshot {
    param([string]$Source, [string]$Destination)
    try {
        Compress-Archive -Path $Source -DestinationPath $Destination -Force
        Write-Log "压缩快照创建成功: $Destination"
        return $true
    }
    catch {
        Write-Log "压缩失败: $_"
        return $false
    }
}
# 清理旧快照
function Cleanup-OldSnapshots {
    Write-Log "开始清理 $RetentionDays 天前的旧快照..."
    $OldSnapshots = Get-ChildItem -Path $SnapshotDir -Filter "*.zip" |
        Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$RetentionDays) }
    foreach ($Old in $OldSnapshots) {
        Remove-Item $Old.FullName -Force
        Write-Log "删除旧快照: $($Old.Name)"
    }
    Write-Log "清理完成,剩余快照数量: $(Get-ChildItem -Path $SnapshotDir -Filter "*.zip").Count"
}
# 主函数
function Main {
    Write-Log "系统快照脚本启动"
    try {
        # 创建系统信息快照
        Create-SystemInfoSnapshot
        # 压缩快照
        $ZipFile = "$SnapshotDir\$SnapshotName.zip"
        if (Compress-Snapshot -Source $SnapshotPath -Destination $ZipFile) {
            # 删除临时目录
            Remove-Item -Path $SnapshotPath -Recurse -Force
            # 清理旧快照
            Cleanup-OldSnapshots
            Write-Log "系统快照创建成功: $ZipFile"
            # 显示当前快照列表
            Write-Log "当前快照列表:"
            Get-ChildItem -Path $SnapshotDir -Filter "*.zip" | 
                Select-Object Name, @{Name="Size(MB)";Expression={$_.Length/1MB}}, LastWriteTime
        }
    }
    catch {
        Write-Log "错误: $_"
    }
    Write-Log "系统快照脚本执行完成"
}
# 运行主函数
Main

定时任务配置脚本

Linux Crontab 配置

# Linux定时任务配置
# 每天凌晨2点执行系统快照
echo "0 2 * * * /usr/local/bin/system_snapshot.sh" | crontab -
# 或者添加到现有crontab(推荐)
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/system_snapshot.sh") | crontab -

Windows 任务计划程序配置

# Windows定时任务配置
# 创建每天凌晨2点执行的任务
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File `"C:\Scripts\create-snapshot.ps1`""
$Trigger = New-ScheduledTaskTrigger -Daily -At "02:00"
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName "SystemSnapshot" -Action $Action -Trigger $Trigger -Settings $Settings

配置文件示例

创建配置文件 snapshot_config.ini

[System]
# 快照目录
snapshot_dir=/var/backups/system_snapshots
# 保留天数
retention_days=7
# 日志文件
log_file=/var/log/snapshot.log
# 是否压缩快照
compress=yes
# 是否清理旧快照
cleanup_old=yes
选项
backup_system_info=yes
backup_packages=yes
backup_crontab=yes
backup_passwd=yes
backup_partition=yes

使用方法

Linux系统:

# 安装到指定位置
sudo cp system_snapshot.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/system_snapshot.sh
# 手动执行一次
sudo /usr/local/bin/system_snapshot.sh
# 配置定时任务
crontab -e
# 添加:0 2 * * * /usr/local/bin/system_snapshot.sh

Windows系统:

# 执行脚本
powershell -ExecutionPolicy Bypass -File "C:\Scripts\create-snapshot.ps1"
# 配置定时任务
schtasks /create /tn "SystemSnapshot" /tr "powershell -ExecutionPolicy Bypass -File C:\Scripts\create-snapshot.ps1" /sc daily /st 02:00

高级功能扩展

您可以根据需要添加更多功能:

  1. 数据库备份:添加MySQL/PostgreSQL备份
  2. 远程备份:将快照上传到远程服务器或云存储
  3. 邮件通知:快照完成后发送邮件通知
  4. 完整性校验:生成MD5校验和
  5. 监控告警:监控快照空间使用率

这个脚本提供了完整的系统快照功能,您可以根据实际需求进行调整和扩展。

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