网盘在个人手里是存储,在开发者手里是基础设施。如果你的项目需要定期把日志、备份、生成产物自动传到云端,阿里云盘的开放API和WebDAV接口是可以直接用的——不需要手动拖拽,脚本搞定。

本文从零开始,用Python实现三个最常用的自动化场景:批量上传、按规则重命名、目录同步


一、准备工作:获取WebDAV凭据

阿里云盘的WebDAV在「开发者」页面开通,不是所有人都知道这个入口,但它确实是目前最稳定的文件操作通道——不需要走OAuth,不需要app注册,一个地址+账号+密码就能读写。

获取步骤

1.登录阿里云盘网页版 → 右上角头像 →账号管理
2.左侧菜单 →**「开发者」「WebDAV」**
3.点击**「创建」**,获得一组凭据

参数
地址 https://dav.aliyundrive.com
用户名 注册手机号
密码 生成的一次性字符串(只显示一次)

二、安装依赖

pip install webdavclient3

为什么用 webdavclient3 而不是手写HTTP请求:WebDAV协议本身是HTTP扩展,操作方法(PROPFIND/PUT/DELETE/MOVE)在标准库 requests里得自己拼。这个库封装了所有操作,代码量可以少一半。


三、客户端封装

from webdav3.client import Client
import os

class AliDrive:
    def __init__(self, username, password):
        options = {
            'webdav_hostname': 'https://dav.aliyundrive.com',
            'webdav_login':    username,
            'webdav_password': password
        }
        self.client = Client(options)

    def list(self, remote_path="/"):
        """列出目录内容"""
        return self.client.list(remote_path)

    def upload(self, local_path, remote_path):
        """上传单个文件"""
        self.client.upload_sync(remote_path=remote_path, local_path=local_path)
        print(f"  ✓ {local_path}{remote_path}")

    def download(self, remote_path, local_path):
        self.client.download_sync(remote_path=remote_path, local_path=local_path)

    def mkdir(self, path):
        self.client.mkdir(path)

    def exists(self, path):
        return self.client.check(path)

    def delete(self, path):
        self.client.clean(path)

upload_sync 是同步上传,适合批量脚本不需要回调的场景。如果是超大文件(>1GB),换用 upload_async加回调监控进度。


四、场景1:批量上传并按日期归档

把本地 D:\backups\ 下的所有 .sql文件上传到云盘,按当天日期创建子目录:

import glob
from datetime import datetime

def batch_upload_backups(ali: AliDrive, local_dir: str, remote_base="/backups"):
    today = datetime.now().strftime("%Y-%m-%d")
    remote_dir = f"{remote_base}/{today}"

    if not ali.exists(remote_dir):
        ali.mkdir(remote_dir)
        print(f"创建目录: {remote_dir}")

    files = glob.glob(f"{local_dir}/*.sql")
    print(f"待上传: {len(files)} 个文件")

    for f in files:
        fname = os.path.basename(f)
        ali.upload(f, f"{remote_dir}/{fname}")

    print(f"完成: {len(files)} 个文件已上传至 {remote_dir}")

# 使用示例
ali = AliDrive("138****1234", "your_webdav_password")
batch_upload_backups(ali, r"D:\backups")

实际使用时会配合 crontab或 Windows任务计划程序,每天凌晨自动执行一次。


五、场景2:按规则批量重命名

云盘里有一个文件夹存了几百张截图,命名是时间戳 20260710_143022.png,想改成 screenshot_001.png这种递增编号。

常规做法是下载→本地改名→重新上传。用WebDAV的MOVE操作可以直接在云端改名,不需要下载:

def batch_rename_in_cloud(ali: AliDrive, remote_dir: str, prefix: str, ext: str):
    """云端批量重命名:把某个目录下的文件改为 prefix_001.ext, prefix_002.ext ..."""
    files = ali.list(remote_dir)
    # 过滤指定扩展名的文件
    targets = [f for f in files if f.endswith(f".{ext}")]

    print(f"找到 {len(targets)} 个 .{ext} 文件,开始重命名...")
    for i, f in enumerate(targets, start=1):
        old_path = f"{remote_dir}/{f}"
        new_path = f"{remote_dir}/{prefix}_{i:03d}.{ext}"
        ali.client.move(old_path, new_path)
        print(f"  {f}{prefix}_{i:03d}.{ext}")

# 把 /screenshots/ 下所有 png 按 screenshot_001 重命名
batch_rename_in_cloud(ali, "/screenshots", "screenshot", "png")

核心是 client.move()——WebDAV的MOVE指令,等价于重命名+移动。阿里云盘对这个操作的支持是完整的,不走下载再上传,几百个文件几秒完成。


六、场景3:增量目录同步

把本地工作目录和云端某个目录保持同步——新增文件上传,本地已删除的文件从云端移除:

def sync_to_cloud(ali: AliDrive, local_dir: str, remote_dir: str):
    """增量同步:本地→云端"""
    if not ali.exists(remote_dir):
        ali.mkdir(remote_dir)

    # 本地文件集合
    local_files = set(os.listdir(local_dir))
    # 云端文件集合(去除路径前缀)
    remote_files = set(ali.list(remote_dir))

    # 新增:本地有、云端没有
    new_files = local_files - remote_files
    for f in new_files:
        local_path = os.path.join(local_dir, f)
        if os.path.isfile(local_path):
            ali.upload(local_path, f"{remote_dir}/{f}")

    # 删除:云端有、本地没有
    deleted = remote_files - local_files
    for f in deleted:
        ali.delete(f"{remote_dir}/{f}")
        print(f"  删除: {f}")

    print(f"同步完成: +{len(new_files)} -{len(deleted)}")

# 把本地项目产物的 output/ 目录同步到云端 /project-output/
sync_to_cloud(ali, "./output", "/project-output")

七、实际集成:GitHub Actions 自动备份构建产物

最后给一个真实场景——CI/CD中把构建产物上传到阿里云盘:

# .github/workflows/backup.yml
- name: Build
  run: npm run build
- name: Upload to AliyunDrive
  env:
    ALI_USER: ${{ secrets.ALI_USER }}
    ALI_PASS: ${{ secrets.ALI_PASS }}
  run: |
    pip install webdavclient3
    python scripts/upload_build.py ./dist /builds/$(date +%Y%m%d)

这样每次构建后,产物自动归档到云端目录,省了手动备份和清理服务器空间的麻烦。


八、注意事项

  • 频率限制:阿里云盘WebDAV有请求频率限制,批量操作时建议每次请求间隔0.5-1秒,否则可能收到429 Too Many Requests
  • 文件名:WebDAV路径中不要包含 ?<>:*|"等Windows非法字符,否则MOVE操作会失败。
  • 大文件:超过2GB的文件建议走分片上传,直接PUT可能超时。webdavclient3upload_chunks方法,查阅文档配置即可。

阿里云盘客户端可从这里获取(WebDAV需在网页端开发者页面开启):

下载地址:阿里云盘最新下载


Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐