Python ftplib在Ubuntu系统下载文件为空,在Fedora正常,如何解决?
null
Python ftplib在Ubuntu系统下载文件为空,在Fedora正常,如何解决?
1 回复
我遇到过类似问题,通常是Ubuntu系统上FTP服务器的被动模式配置差异导致的。试试在代码中显式设置被动模式:
from ftplib import FTP
import os
def download_file(host, username, password, remote_path, local_path):
with FTP(host) as ftp:
ftp.login(username, password)
# 关键设置:强制使用被动模式
ftp.set_pasv(True) # Ubuntu通常需要这个
with open(local_path, 'wb') as local_file:
ftp.retrbinary(f'RETR {remote_path}', local_file.write)
# 验证文件大小
local_size = os.path.getsize(local_path)
ftp.sendcmd('TYPE I') # 切换到二进制模式获取远程文件大小
remote_size = ftp.size(remote_path)
print(f"本地文件大小: {local_size} bytes")
print(f"远程文件大小: {remote_size} bytes")
return local_size == remote_size
# 使用示例
if __name__ == "__main__":
success = download_file(
host='your.ftp.server.com',
username='your_username',
password='your_password',
remote_path='/path/to/remote/file.txt',
local_path='./downloaded_file.txt'
)
print(f"下载{'成功' if success else '失败'}")
如果还不行,可能是防火墙或网络配置问题,检查Ubuntu的UFW设置。

