Spaces:
Paused
Paused
| set -e # 任何命令失败立即退出 | |
| # 检查WebDAV配置 | |
| check_webdav() { | |
| if [ -z "${WEBDAV_URL}" ] || [ -z "${WEBDAV_USERNAME}" ] || [ -z "${WEBDAV_PASSWORD}" ]; then | |
| echo "WebDAV配置缺失,跳过备份操作" | |
| exit 0 | |
| fi | |
| } | |
| # 恢复备份函数 | |
| restore() { | |
| echo "=== 开始恢复备份 ===" | |
| check_webdav | |
| # Python恢复脚本 | |
| python3 <<EOF | |
| import os | |
| import sys | |
| from webdav3.client import Client | |
| try: | |
| # 初始化客户端 | |
| client = Client({ | |
| 'webdav_hostname': os.getenv('WEBDAV_URL'), | |
| 'webdav_login': os.getenv('WEBDAV_USERNAME'), | |
| 'webdav_password': os.getenv('WEBDAV_PASSWORD') | |
| }) | |
| # 查找最新备份 | |
| backups = [f for f in client.list() | |
| if f.startswith('alist_backup_') and f.endswith('.tar.gz')] | |
| if not backups: | |
| print("未找到有效备份文件") | |
| sys.exit(0) | |
| latest = sorted(backups)[-1] | |
| print(f"正在恢复备份: {latest}") | |
| # 下载并解压 | |
| tmp_file = f"/tmp/{latest}" | |
| client.download_sync(latest, tmp_file) | |
| # 清空目标目录 | |
| for d in ['/app/data', '/app/config']: | |
| if os.path.exists(d): | |
| os.system(f"rm -rf {d}/*") | |
| # 解压到根目录 | |
| os.system(f"tar -xzf {tmp_file} -C /") | |
| os.remove(tmp_file) | |
| print("备份恢复完成!") | |
| except Exception as e: | |
| print(f"恢复失败: {str(e)}") | |
| sys.exit(1) | |
| EOF | |
| } | |
| # 定时同步函数 | |
| sync() { | |
| while true; do | |
| echo "$(date) 同步数据到WebDAV..." | |
| BACKUP_FILE="alist_backup_$(date +%Y%m%d_%H%M%S).tar.gz" | |
| # 打包数据 | |
| tar -czf "/tmp/${BACKUP_FILE}" -C / app/data app/config | |
| # 上传 | |
| python3 -c " | |
| from webdav3.client import Client | |
| client = Client({ | |
| 'webdav_hostname': '${WEBDAV_URL}', | |
| 'webdav_login': '${WEBDAV_USERNAME}', | |
| 'webdav_password': '${WEBDAV_PASSWORD}' | |
| }) | |
| client.upload_sync('${BACKUP_FILE}', '/tmp/${BACKUP_FILE}') | |
| print('上传成功')" | |
| # 清理 | |
| rm -f "/tmp/${BACKUP_FILE}" | |
| sleep ${SYNC_INTERVAL} | |
| done | |
| } | |
| # 根据参数执行 | |
| case "$1" in | |
| restore) | |
| restore | |
| ;; | |
| sync) | |
| sync | |
| ;; | |
| *) | |
| echo "Usage: $0 {restore|sync}" | |
| exit 1 | |
| esac |