FTP脚本下载一组文件

我正在使用FTP脚本从FTP服务器下载所有文件,然后在完成后删除这些文件,但是如果在下载过程中添加了任何文件,则将文件保留在远程服务器上,以便在稍后的会话中进行提取。

是否有可能使用FTP脚本实现这样的事情,还是我需要一个不同的解决scheme。

我打算使用psftp

基于麦克斯韦对这个问题 的回答,我可能会沿着这个伪代码做一些事情:

使用$favorite_scripting_language来收集文件名列表d / l然后杀; 编写一个名为script.txt的输出文件,格式如下:

 cd /source/directory lcd c:\target\directory get foo.bar delete foo.bar <<lather, rinse, repeat>> 

然后把它包起来:

 psftp.exe username@server -be -pw user_password -bc:\script.txt 

如何python? 作为一个加号,它应该在任何操作系统上或多或less地不加修改地工作。 更重要的是,使用其他更脆弱的方法更为灵活。

它会像这样:

 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也可以做到这一点,它可能看起来差不多。