我需要一个 FTP 脚本来从 FTP 服务器下载所有文件,然后在完成后删除这些文件,但如果在下载过程中添加了任何文件,则将其保留在远程服务器上,以便在以后的会话中获取。
是否可以使用 FTP 脚本实现这样的功能,或者我是否需要其他解决方案。
我原本打算使用 psftp。
答案1
答案2
那 Python 呢?优点是它应该可以在任何操作系统上几乎不加修改地运行。更大的优点是它比使用其他更脆弱的方法更灵活。
它会是这样的:
from ftplib import FTP
import os
ftp = FTP("server")
ftp.login("id", "passwd")
ftp.cwd("/server/ftpdir/")
#copy every file as usual to local system
filelist = []
ftp.retrlines('LIST', filelist.append)
### the list filelist will have one element per file
### which you will have to cut up into the proper pieces
### among Python's installed files on your system is
### the script Tools/scripts/ftpmirror.py which has such code
### it starts at around line 140 (for python 2.6.1)
### --- not very long but this margin is too small to contain it
### assume the file names are in dictionary filedict
### keys are filenames and values are file sizes
for fname in filedict.keys():
localfname = os.path.join(localdir, fname) # set localdir to cwd or whatever
lf = open(localfname , "wb")
ftp.retrbinary('RETR ' + fname, lf.write)
lf.close()
#refresh remote directory listing into filedict2 as with previous filedict
for fname in filedict2.keys():
if fname not in filedict:
# new file since download started! ignore. it's for later
pass
else:
if filedict[fname] == filedict2[fname]:
# apparently we got a good copy so delete the file on ftp server
ftp.delete(fname)
else:
# delete local file: remote was being uploaded or something
os.unlink(os.path.join(localdir, fname))
您必须添加错误检查和其他类似的东西。使用 perl 可以完成相同的操作,并且看起来可能差不多。