目录
- 0、前言
- 1、授权webdav应用
- 2、下载webdavclient3
- 3、替换相关代码
0、前言
最近,我在处理两台服务器间的文件传输问题时遇到了不少难题。这两台服务器并不处于同一内网环境,导致无法通过SFTP进行文件传输。由于这些服务器属于局域网,并且我没有权限修改网络配置,这使得文件传输变得格外头疼,尤其是当文件体积较大时。
为了解决这个问题,我曾尝试通过租用一个云服务器来架设一个中转站。我使用专用客户端连接到服务器B的内网,通过sock5或http协议连接到我的中转服务器。尽管这种方法可行,但由于使用华为云服务器的带宽限制为4Mb,相当于0.5MB/s的传输速度,这让大文件的传输效率极低,让人十分崩溃。
最近发现了支持WebDAV协议的国内123云盘。通过简单的Python编程,实现文件的上传和下载功能,这样就大大减少了对中转服务器的依赖。感觉还是很开心的
1、授权webdav应用
123云盘注册:123云盘个人中心(有aff)
123云盘注册:123云盘(无aff)
这里面的服务器地址对应webdav_hostname
账户对应 webdav_login
应用密码对应 webdav_password
【首次使用请创建应用】
2、下载webdavclient3
pip install webdavclient3
3、替换相关代码
请将如下代码中的webdav_hostname、webdav_login、webdav_password
替换成自己的
from webdav3.client import Client
from webdav3.exceptions import RemoteResourceNotFound
import os# WebDAV配置
config = {'webdav_hostname': "*******",'webdav_login': "*******",'webdav_password': "*******"
}def upload_file_or_folder(client, local_path, remote_path):if os.path.isdir(local_path):# 上传整个文件夹client.upload_sync(remote_path=remote_path, local_path=local_path)print(f"Folder '{local_path}' has been uploaded to '{remote_path}'.")elif os.path.isfile(local_path):# 上传单个文件client.upload_sync(remote_path=remote_path, local_path=local_path)print(f"File '{local_path}' has been uploaded to '{remote_path}'.")else:print("The specified path does not exist.")def download_file_or_folder(client, remote_path, local_path):try:if client.check(remote_path): # 检查远程路径是否存在# 下载文件或文件夹client.download_sync(remote_path=remote_path, local_path=local_path)print(f"Resource '{remote_path}' has been downloaded to '{local_path}'.")else:print(f"The resource '{remote_path}' does not exist on the server.")except RemoteResourceNotFound:print(f"No resource found at '{remote_path}'.")except Exception as e:print(f"An error occurred: {e}")def main():client = Client(config)print('client:', client)try:print(client.list())# # 指定本地路径和远程路径local_path = "alphabug.zip"remote_path = "数据备份/alphabug.zip"# 上传文件或文件夹upload_file_or_folder(client, local_path, remote_path)# 下载文件或文件夹#download_file_or_folder(client, remote_path, local_path)except Exception as e:print(f"An error occurred: {e}")if __name__ == "__main__":main()
我把代码放到了123云盘上,可以直接下载。【如果通过分享链接开通会员会走我的aff】
https://www.123pan.com/s/bixmTd-fBGGh.html