本文目录导读:

针对云存储操作,有不少实用脚本能显著提升效率,下面按不同云平台和使用场景分类整理。
跨平台文件同步脚本
# rclone_sync.py - 使用 rclone 进行多平台同步
import subprocess
import json
from datetime import datetime
def sync_to_all_clouds(source_path):
"""
同步本地文件夹到多个云存储
"""
clouds = {
"google_drive": "gdrive:backup",
"onedrive": "onedrive:backup",
"dropbox": "dropbox:backup"
}
for cloud_name, remote_path in clouds.items():
cmd = f"rclone sync {source_path} {remote_path} --progress --log-file=sync_{cloud_name}_{datetime.now().strftime('%Y%m%d')}.log"
subprocess.run(cmd, shell=True)
批量文件上传脚本
#!/bin/bash
# batch_upload.sh - 批量上传到 AWS S3 或兼容存储
# 上传当前目录所有 .mp4 文件到 S3
for file in *.mp4; do
if [ -f "$file" ]; then
echo "Uploading $file..."
aws s3 cp "$file" "s3://my-bucket/videos/$file" --storage-class STANDARD_IA
# 成功上传后删除本地文件(可选)
if [ $? -eq 0 ]; then
rm "$file"
echo "Uploaded and removed $file"
fi
fi
done
备份脚本:带日期版本
# backup_with_timestamp.py
import shutil
import os
from datetime import datetime
import boto3
def backup_to_s3_with_version(local_path, bucket_name):
"""
带时间戳自动备份到 S3
"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
s3_key = f"backups/{os.path.basename(local_path)}_{timestamp}"
s3 = boto3.client('s3')
s3.upload_file(local_path, bucket_name, s3_key)
print(f"Backup completed: {s3_key}")
本地文件自动清理脚本
# auto_cleanup.py - 删除超过7天的已同步文件
import os
import time
from datetime import datetime, timedelta
def cleanup_old_files(directory, max_days=7):
"""
删除指定目录下超过设定天数的文件
"""
cutoff = time.time() - (max_days * 86400)
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath) and os.path.getmtime(filepath) < cutoff:
os.remove(filepath)
print(f"Deleted: {filename}")
跨云存储迁移脚本
#!/bin/bash # migrate_across_clouds.sh - 从本地或旧云迁移到新云 # 使用 rclone 直接跨云传输 rclone copy gdrive:old_project onedrive:new_project -P --transfers 8 # 或使用 aws cli 从 S3 到本地 aws s3 sync s3://old-bucket/ . --exclude "*.tmp" # 再上传到新云存储 rclone copy . newcloud:mydata --progress
定时监控和通知脚本
# cloud_monitor.py - 监控存储使用情况
import requests
import json
from twilio.rest import Client
def check_storage_limit(provider="google"):
"""
检查云存储使用量,超过阈值发送通知
"""
usage_urls = {
"google": "https://www.googleapis.com/drive/v3/about",
"onedrive": "https://graph.microsoft.com/v1.0/me/drive"
}
# 实际使用需要 OAuth 认证
response = requests.get(usage_urls[provider], headers={"Authorization": "Bearer YOUR_TOKEN"})
data = response.json()
usage_percent = (data['storageQuota']['usage'] / data['storageQuota']['limit']) * 100
if usage_percent > 80:
# 发送短信或邮件通知
client = Client("TWILIO_SID", "TWILIO_AUTH_TOKEN")
client.messages.create(
body=f"Alert: {provider.capitalize()} storage at {usage_percent:.1f}%",
from_="+1234567890",
to="+0987654321"
)
智能文件分类上传脚本
# auto_classify_upload.py
import mimetypes
import os
import shutil
def classify_and_upload(src_dir, cloud_root):
"""
根据文件类型自动分类上传到不同云文件夹
"""
for root, dirs, files in os.walk(src_dir):
for file in files:
file_path = os.path.join(root, file)
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type:
main_type = mime_type.split('/')[0]
dest_folder = {
"image": "images",
"video": "videos",
"audio": "audios",
"application": "documents",
}.get(main_type, "others")
cloud_path = os.path.join(cloud_root, dest_folder, file)
# 这里替换为实际云存储上传函数
upload_to_cloud(file_path, cloud_path)
增量备份脚本
#!/bin/bash # incremental_backup.sh - 使用 rsync 进行增量备份 # 本地目录到云存储 rsync -avz --delete --progress /local/data/ user@cloud-server:/backup/data/ # 排除临时文件和缓存 rsync -avz --exclude="*.tmp" --exclude="cache/" /local/data/ remote:/backup/data/
使用建议
-
安装必要工具:
- macOS:
brew install rclone - Linux:
sudo apt install rclone - Windows: 下载 rclone.exe
- macOS:
-
配置认证:
- rclone:
rclone config交互式设置 - AWS CLI:
aws configure - gsutil:
gcloud auth login
- rclone:
-
安全考虑:
- 使用环境变量存储密钥:
export CLOUD_KEY="xxx" - 避免在脚本中硬编码凭据
- 使用 .gitignore 排除配置文件
- 使用环境变量存储密钥:
-
定时执行:
- Linux/macOS: 使用 crontab
- Windows: 使用任务计划程序
- macOS: 使用 launchd
这些脚本可以根据实际需求组合使用,建议先从简单的单文件上传测试开始,逐步扩展到复杂的工作流。