import ftplib
import time
# FTP 服务器的地址、用户名和密码
server_address = "192.168.10.1"
username = "zhangsan"
password = "*****!"
# 要下载的文件的路径
remote_path = "/tmp/ftp1"
# 要保存的文件的本地路径
local_path = "d:/testftp"
# 设置每隔 5 秒执行一次
interval = 5
# 日志文件的路径
log_file = "d:/testftp/file.log"
while True:
try:
# 连接到 FTP 服务器
ftp = ftplib.FTP(server_address)
ftp.encoding = 'utf8'
ftp.login(username, password)
# 启用被动模式
ftp.set_pasv(True)
# 将当前工作目录设置为要下载的文件的目录
ftp.cwd(remote_path)
# 获取要下载的文件的列表
file_list = ftp.nlst()
for filename in file_list:
# 尝试下载文件
with open(f"{local_path}/{filename}", "wb") as f:
ftp.retrbinary(f"RETR {filename}", f.write)
# 如果下载成功,删除文件
ftp.delete(filename)
# 将成功信息写入日志文件
with open(log_file, "a") as f:
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
f.write(f"{current_time} Successfully downloaded and deleted {filename}\n")
# 关闭连接
ftp.close()
except Exception as e:
# 将异常信息写入日志文件
with open(log_file, "a") as f:
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
f.write(f"{current_time} Error : {e}\n")
# 等待 5 秒后再次执行
time.sleep(interval)
标签:FTP,ftp,filename,文件,file,time,服务器,ChartGPT
From: https://www.cnblogs.com/marit/p/16988278.html