前言
接了个特别小的活,要求说定期给文件打包然后上传到备份服务器内,于是整了这么个玩意,记录一下,说不准以后有用
正文
环境:Python 3.7.4
废话少说上码
import os, time, zipfile, ftplib # 导入需要的模块
t = time.strftime('%Y-%m-%d',time.localtime(time.time()))
ftp = ftplib.FTP("ftp服务器IP")
ftp.login("用户名", "密码") # 登陆ftp服务器
def make_zip(source_dir, output_filename): # 定义打包函数
zipf = zipfile.ZipFile(output_filename, 'w')
pre_len = len(os.path.dirname(source_dir))
for parent, dirnames, filenames in os.walk(source_dir):
for filename in filenames:
pathfile = os.path.join(parent, filename)
arcname = pathfile[pre_len:].strip(os.path.sep)
zipf.write(pathfile, arcname)
zipf.close()
make_zip('文件URL地址',"%s.zip"%t) # 将文件打包成 年-月-日.zip
def ftp_upload(): # 定义上传函数
file_remote = '%s.zip'%t
file_local = './%s.zip'%t
bufsize = 1024
fp = open(file_local, 'rb')
ftp.storbinary('STOR ' + file_remote, fp, bufsize)
fp.close()
ftp_upload() # 将文件上传至服务器
ftp.quit() # 退出ftp服务器
exit() # 代码结束
定期的话搞个计划任务就行了
(话说最近黑客活动有点多啊