本文目录导读:

我来为您介绍编写自动下载补丁并安装的脚本方法,以下是针对不同操作系统的示例:
Windows PowerShell 脚本
下载并安装 MSI 补丁
# 补丁下载并安装脚本
$patchUrl = "https://example.com/patch/update.msi"
$patchPath = "$env:TEMP\update.msi"
$logFile = "C:\patch_install.log"
# 下载补丁
Write-Host "正在下载补丁..."
try {
Invoke-WebRequest -Uri $patchUrl -OutFile $patchPath
Write-Host "补丁下载完成" | Out-File $logFile -Append
} catch {
Write-Error "下载失败: $_"
exit 1
}
# 安装补丁
Write-Host "正在安装补丁..."
$process = Start-Process -FilePath "msiexec.exe" -ArgumentList "/i `"$patchPath`" /quiet /norestart" -Wait -PassThru
if ($process.ExitCode -eq 0) {
Write-Host "安装成功" | Out-File $logFile -Append
} else {
Write-Error "安装失败,退出代码: $($process.ExitCode)"
exit 1
}
# 清理
Remove-Item $patchPath -Force
Linux Bash 脚本
下载并安装 .deb 或 .rpm 包
#!/bin/bash
# 配置变量
PATCH_URL="https://example.com/patch/update.deb"
PATCH_FILE="/tmp/update.deb"
LOG_FILE="/var/log/patch_install.log"
# 记录日志函数
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOG_FILE
echo "$1"
}
# 下载补丁
log "开始下载补丁..."
if wget -O $PATCH_FILE $PATCH_URL 2>&1; then
log "补丁下载完成"
else
log "下载失败"
exit 1
fi
# 验证文件完整性(可选)
log "验证文件完整性..."
md5sum $PATCH_FILE >> $LOG_FILE
# 安装补丁
log "开始安装补丁..."
case "$OSTYPE" in
debian*|ubuntu*)
if sudo dpkg -i $PATCH_FILE 2>&1; then
log "安装成功"
else
log "安装失败,尝试修复..."
sudo apt-get install -f -y
fi
;;
rhel*|centos*|fedora*)
if sudo rpm -ivh $PATCH_FILE 2>&1; then
log "安装成功"
else
log "安装失败"
exit 1
fi
;;
*)
log "不支持的操作系统"
exit 1
;;
esac
# 清理
rm -f $PATCH_FILE
log "补丁安装完成"
高级版本 - 带错误处理和回滚
#!/usr/bin/env python3
"""
自动下载和安装补丁脚本
支持多平台,带错误处理和回滚机制
"""
import os
import sys
import hashlib
import logging
import platform
import subprocess
import requests
from pathlib import Path
class PatchInstaller:
def __init__(self, config):
self.config = config
self.setup_logging()
self.backup_files = []
def setup_logging(self):
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('patch_install.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
def download_patch(self):
"""下载补丁文件"""
self.logger.info("开始下载补丁...")
try:
response = requests.get(
self.config['url'],
stream=True,
timeout=30
)
response.raise_for_status()
with open(self.config['local_path'], 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
self.logger.info("补丁下载完成")
return True
except Exception as e:
self.logger.error(f"下载失败: {e}")
return False
def verify_integrity(self):
"""验证文件完整性"""
if 'md5' not in self.config:
return True
self.logger.info("验证文件完整性...")
md5_hash = hashlib.md5()
with open(self.config['local_path'], 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
md5_hash.update(chunk)
if md5_hash.hexdigest() != self.config['md5']:
self.logger.error("文件校验失败")
return False
return True
def create_backup(self):
"""创建重要文件备份"""
self.logger.info("创建文件备份...")
backup_dir = Path("/tmp/patch_backup")
backup_dir.mkdir(exist_ok=True)
for file_path in self.config.get('backup_files', []):
if os.path.exists(file_path):
backup_path = backup_dir / Path(file_path).name
try:
subprocess.run(['cp', '-r', file_path, str(backup_path)], check=True)
self.backup_files.append((file_path, str(backup_path)))
self.logger.info(f"备份 {file_path} 完成")
except Exception as e:
self.logger.warning(f"备份 {file_path} 失败: {e}")
def install_patch(self):
"""安装补丁"""
self.logger.info("开始安装补丁...")
system = platform.system().lower()
patch_path = self.config['local_path']
try:
if system == "linux":
if patch_path.endswith('.deb'):
result = subprocess.run(
['sudo', 'dpkg', '-i', patch_path],
capture_output=True,
text=True
)
elif patch_path.endswith('.rpm'):
result = subprocess.run(
['sudo', 'rpm', '-ivh', patch_path],
capture_output=True,
text=True
)
else:
# 可执行文件
result = subprocess.run(
['chmod', '+x', patch_path],
capture_output=True
)
result = subprocess.run(
['sudo', patch_path],
capture_output=True,
text=True
)
elif system == "windows":
if patch_path.endswith('.msi'):
result = subprocess.run(
['msiexec', '/i', patch_path, '/quiet', '/norestart'],
capture_output=True,
text=True
)
else:
result = subprocess.run(
[patch_path, '/silent', '/norestart'],
capture_output=True,
text=True
)
else:
self.logger.error(f"不支持的操作系统: {system}")
return False
if result.returncode == 0:
self.logger.info("安装成功")
return True
else:
self.logger.error(f"安装失败: {result.stderr}")
return False
except Exception as e:
self.logger.error(f"安装过程出错: {e}")
return False
def rollback(self):
"""回滚操作"""
self.logger.info("开始回滚...")
for original, backup in self.backup_files:
try:
subprocess.run(['cp', '-r', backup, original], check=True)
self.logger.info(f"回滚 {original} 完成")
except Exception as e:
self.logger.error(f"回滚 {original} 失败: {e}")
def cleanup(self):
"""清理临时文件"""
self.logger.info("清理临时文件...")
if os.path.exists(self.config['local_path']):
os.remove(self.config['local_path'])
# 清理备份
for _, backup in self.backup_files:
if os.path.exists(backup):
os.remove(backup)
def run(self):
"""执行安装流程"""
try:
# 1. 创建备份
self.create_backup()
# 2. 下载补丁
if not self.download_patch():
return False
# 3. 验证完整性
if not self.verify_integrity():
self.rollback()
return False
# 4. 安装补丁
if not self.install_patch():
self.rollback()
return False
# 5. 清理
self.cleanup()
return True
except Exception as e:
self.logger.error(f"安装流程出错: {e}")
self.rollback()
return False
# 使用示例
if __name__ == "__main__":
config = {
'url': 'https://example.com/patch/update.deb',
'local_path': '/tmp/patch_update.deb',
'md5': 'd41d8cd98f00b204e9800998ecf8427e', # 示例MD5
'backup_files': [
'/etc/important_config.conf',
'/var/lib/important_data.db'
]
}
installer = PatchInstaller(config)
if installer.run():
print("补丁安装成功!")
sys.exit(0)
else:
print("补丁安装失败!")
sys.exit(1)
配置文件和定时任务
配置文件示例 (config.json)
{
"patches": [
{
"name": "security_update_2024",
"url": "https://patches.example.com/update_2024.msi",
"md5": "xxx...",
"backup_files": ["C:/config/app.config"],
"install_type": "msi",
"install_params": ["/quiet", "/norestart"]
}
],
"schedule": {
"enabled": true,
"cron": "0 2 * * 0", // 每周日凌晨2点
"max_retries": 3
}
}
定时任务配置
# Linux crontab 配置 0 2 * * 0 /usr/local/bin/auto_patch_installer.sh >> /var/log/auto_patch.log 2>&1 # Windows 任务计划程序 PowerShell $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\scripts\auto_patch.ps1" $trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2am $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest Register-ScheduledTask -TaskName "AutoPatchInstaller" -Action $action -Trigger $trigger -Principal $principal
使用建议
- 测试环境验证:先在测试环境运行
- 备份重要数据:定期备份关键配置
- 监控和日志:记录所有操作日志
- 错误处理:添加重试机制和告警
- 安全性:验证文件签名和完整性
根据需要选择适合您平台的版本,并适当修改URL和安装参数。