72 lines
3.0 KiB
Python
72 lines
3.0 KiB
Python
import os
|
||
import ftplib
|
||
import socks
|
||
import socket
|
||
from urllib.parse import urlparse
|
||
|
||
def set_proxy(proxy_url):
|
||
"""设置代理"""
|
||
if proxy_url:
|
||
parsed_proxy = urlparse(proxy_url)
|
||
proxy_host = parsed_proxy.hostname
|
||
proxy_port = parsed_proxy.port
|
||
socks.set_default_proxy(socks.SOCKS5, proxy_host, proxy_port) # 可以根据需要调整为 SOCKS5、SOCKS4 或 HTTP
|
||
socket.socket = socks.socksocket
|
||
print(f"已设置代理: {proxy_host}:{proxy_port}")
|
||
|
||
def upload_file_to_ftp(server, username, password, file_path, remote_path):
|
||
"""上传单个文件到FTP"""
|
||
try:
|
||
|
||
|
||
with ftplib.FTP(server) as ftp:
|
||
ftp.login(user=username, passwd=password)
|
||
with open(file_path, 'rb') as file:
|
||
ftp.storbinary(f'STOR {remote_path}', file)
|
||
print(f"文件 {file_path} 成功上传到 {remote_path}!")
|
||
|
||
except ftplib.all_errors as e:
|
||
print(f"FTP 错误: {e}")
|
||
except Exception as e:
|
||
print(f"发生错误: {e}")
|
||
|
||
def create_remote_directory(ftp, remote_directory):
|
||
"""确保远程目录存在,如果不存在则创建"""
|
||
try:
|
||
ftp.cwd(remote_directory) # 尝试进入远程目录
|
||
except ftplib.error_perm:
|
||
ftp.mkd(remote_directory) # 如果远程目录不存在,则创建
|
||
ftp.cwd(remote_directory) # 再次进入远程目录
|
||
print(f"远程目录 {remote_directory} 已创建!")
|
||
|
||
def upload_directory_to_ftp(server, username, password, local_directory, remote_directory):
|
||
"""上传整个目录及其子目录到FTP服务器"""
|
||
try:
|
||
with ftplib.FTP(server) as ftp:
|
||
ftp.login(user=username, passwd=password)
|
||
|
||
# 确保远程目录存在
|
||
create_remote_directory(ftp, remote_directory)
|
||
|
||
# 遍历本地目录树
|
||
for root, dirs, files in os.walk(local_directory):
|
||
# 上传子文件夹
|
||
for dir_name in dirs:
|
||
remote_dir_path = os.path.join(remote_directory, os.path.relpath(os.path.join(root, dir_name), local_directory)).replace("\\", "/")
|
||
try:
|
||
ftp.mkd(remote_dir_path) # 在FTP服务器上创建子目录
|
||
print(f"已创建远程目录: {remote_dir_path}")
|
||
except ftplib.error_perm:
|
||
pass # 如果目录已经存在则忽略
|
||
|
||
# 上传文件
|
||
for filename in files:
|
||
local_file_path = os.path.join(root, filename) # 本地文件的完整路径
|
||
relative_path = os.path.relpath(local_file_path, local_directory) # 计算相对路径
|
||
remote_file_path = os.path.join(remote_directory, relative_path).replace("\\", "/") # 计算远程文件路径
|
||
upload_file_to_ftp(server, username, password, local_file_path, remote_file_path, proxy_url) # 上传文件
|
||
|
||
except ftplib.all_errors as e:
|
||
print(f"上传目录时发生错误: {e}")
|
||
except Exception as e:
|
||
print(f"发生错误: {e}") |