本文目录导读:

- 基于rsync的Linux/Mac同步脚本
- Python增量同步脚本(支持更多特性)
- 定时执行脚本(crontab配置)
- 排除文件示例(exclude_list.txt)
- 增强版rsync脚本(带邮件通知)
- 使用方法
- 注意事项
我来帮你实现一个网盘增量同步脚本,这里提供几种常用的实现方式:
基于rsync的Linux/Mac同步脚本
#!/bin/bash
# rsync_incremental_sync.sh
# 配置参数
SOURCE_DIR="/path/to/source"
DEST_DIR="/path/to/destination"
SYNC_LOG="/var/log/rsync_sync.log"
EXCLUDE_FILE="/path/to/exclude_list.txt"
# 时间戳
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
# 同步函数
sync_files() {
echo "[$TIMESTAMP] 开始增量同步..." >> $SYNC_LOG
# 使用rsync进行增量同步
rsync -avz --delete --progress \
--log-file=$SYNC_LOG \
--exclude-from=$EXCLUDE_FILE \
--link-dest=/path/to/previous_sync \
$SOURCE_DIR/ \
$DEST_DIR/
if [ $? -eq 0 ]; then
echo "[$TIMESTAMP] 同步成功完成" >> $SYNC_LOG
else
echo "[$TIMESTAMP] 同步失败,请检查日志" >> $SYNC_LOG
fi
}
# 主程序
echo "========================================" >> $SYNC_LOG
sync_files
Python增量同步脚本(支持更多特性)
#!/usr/bin/env python3
# incremental_sync.py
import os
import hashlib
import json
import shutil
from datetime import datetime
from pathlib import Path
class IncrementalSync:
def __init__(self, source_dir, dest_dir, db_file="sync_db.json"):
self.source_dir = Path(source_dir)
self.dest_dir = Path(dest_dir)
self.db_file = db_file
self.sync_db = self.load_db()
def load_db(self):
"""加载同步数据库"""
if self.db_file.exists():
with open(self.db_file, 'r') as f:
return json.load(f)
return {}
def save_db(self):
"""保存同步数据库"""
with open(self.db_file, 'w') as f:
json.dump(self.sync_db, f, indent=2)
def get_file_hash(self, filepath):
"""计算文件哈希值"""
hasher = hashlib.md5()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest()
def get_file_info(self, filepath):
"""获取文件信息"""
stat = filepath.stat()
return {
'size': stat.st_size,
'mtime': stat.st_mtime,
'hash': self.get_file_hash(filepath)
}
def scan_source(self):
"""扫描源目录"""
files_info = {}
for filepath in self.source_dir.rglob('*'):
if filepath.is_file():
relative_path = str(filepath.relative_to(self.source_dir))
files_info[relative_path] = self.get_file_info(filepath)
return files_info
def sync_files(self):
"""执行增量同步"""
print(f"[{datetime.now()}] 开始增量同步...")
source_files = self.scan_source()
new_files = []
modified_files = []
deleted_files = []
# 检查新增和修改的文件
for filepath, info in source_files.items():
if filepath not in self.sync_db:
new_files.append(filepath)
elif (self.sync_db[filepath]['mtime'] != info['mtime'] or
self.sync_db[filepath]['size'] != info['size']):
modified_files.append(filepath)
# 检查删除的文件
for filepath in self.sync_db:
if filepath not in source_files:
deleted_files.append(filepath)
# 执行同步操作
for filepath in new_files:
source = self.source_dir / filepath
dest = self.dest_dir / filepath
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, dest)
self.sync_db[filepath] = source_files[filepath]
print(f" 新增: {filepath}")
for filepath in modified_files:
source = self.source_dir / filepath
dest = self.dest_dir / filepath
shutil.copy2(source, dest)
self.sync_db[filepath] = source_files[filepath]
print(f" 更新: {filepath}")
for filepath in deleted_files:
dest = self.dest_dir / filepath
if dest.exists():
dest.unlink()
del self.sync_db[filepath]
print(f" 删除: {filepath}")
# 保存同步数据库
self.save_db()
print(f"[{datetime.now()}] 同步完成")
print(f"新增: {len(new_files)}, 修改: {len(modified_files)}, 删除: {len(deleted_files)}")
# 使用示例
if __name__ == "__main__":
sync = IncrementalSync(
source_dir="/path/to/source",
dest_dir="/path/to/destination"
)
sync.sync_files()
定时执行脚本(crontab配置)
# 每天凌晨2点执行同步 0 2 * * * /path/to/rsync_incremental_sync.sh # 每6小时同步一次 0 */6 * * * /path/to/rsync_incremental_sync.sh # 每周一凌晨3点同步 0 3 * * 1 /path/to/rsync_incremental_sync.sh
排除文件示例(exclude_list.txt)
# 排除临时文件 *.tmp *.temp *.log # 排除缓存目录 .cache/ __pycache__/ node_modules/ # 排除大文件 *.iso *.dmg *.zip *.tar.gz # 排除系统文件 .DS_Store Thumbs.db
增强版rsync脚本(带邮件通知)
#!/bin/bash
# advanced_sync.sh
# 配置
SOURCE="/path/to/source"
DEST="user@remote:/path/to/dest"
SSH_KEY="/path/to/ssh_key"
EMAIL="admin@example.com"
LOG="/var/log/advanced_sync.log"
# 函数:发送邮件通知
send_notification() {
local status=$1
local message=$2
echo "$message" | mail -s "[Sync] $status - $(date '+%Y-%m-%d')" $EMAIL
}
# 函数:执行同步
do_sync() {
# rsync参数说明:
# -a: 归档模式
# -v: 详细输出
# -z: 压缩传输
# --delete: 删除目标端多余文件
# --progress: 显示进度
# -e: 指定SSH配置
rsync -avz --delete --progress \
-e "ssh -i $SSH_KEY" \
--exclude-from="/path/to/exclude.txt" \
--link-dest="/path/to/previous_backup" \
$SOURCE/ \
$DEST/ 2>&1 | tee -a $LOG
return ${PIPESTATUS[0]}
}
# 主程序
echo "=== 开始同步: $(date) ===" >> $LOG
if do_sync; then
send_notification "成功" "数据同步成功完成"
echo "同步成功" >> $LOG
else
send_notification "失败" "数据同步失败,请检查系统"
echo "同步失败" >> $LOG
fi
echo "=== 同步结束: $(date) ===" >> $LOG
使用方法
- 保存脚本:将脚本保存到合适的位置
- 设置权限:
chmod +x script.sh - 修改配置:根据实际需求修改源目录和目标目录
- 测试运行:先手动运行测试
- 设置定时:使用crontab设置自动执行
注意事项
- 首次同步:首次同步会传输所有文件,之后只传输变化的部分
- 网络稳定性:建议添加断点续传功能
- 备份策略:建议保留最近几次的备份快照
- 监控告警:添加失败通知机制
- 性能优化:对大文件或大量小文件分别处理
需要根据你的具体使用场景(本地同步、远程同步、特定云盘API等)选择最适合的实现方式。