Batch delete files on FTP older than x days

2020-07-23 05:06发布

问题:

Found several solutions for local, but need one for FTP action:

I have a daily batch script to backup MySQL databases locally, however I also ftp them to a backup server.

Locally, I am using forfiles to delete files older than 14 days:

forfiles -p "C:\whatever" -s -m *.* -d 14 -c "cmd /c del @path"`

The same I would like to do on FTP, once the newest backup files are dumped into FTP server running on Windows Server 2008 R2.

How do I extend my batch file to do this action?

cd\[path to directory where files are saved] 
echo off
echo user [ftp username]>ftpup.dat
echo [ftp password]>>ftpup.dat
echo binary>>ftpup.dat
echo put [FullBackup.%backupdate%.zip]>>ftpup.dat
echo quit>>ftpup.dat
ftp -n -s:ftpup.dat [myserver.com]
del ftpup.dat

回答1:

  1. capture the list of files you are interested in

    echo user [ftp username]>ftpdir.txt
    echo [ftp password]>>ftpdir.txt
    echo dir . ftplist.txt >>ftpdir.txt
    echo quit>>ftpdir.txt
    ftp -n -s:ftpdir.txt [myserver.com]
    
  2. prepare the ftp delete script

    echo user [ftp username]>ftpdel.txt
    echo [ftp password]>>ftpdel.txt
    
  3. process the list

     for /f "tokens=6,7,8,*" %%a in (ftplist.txt) do (
        echo %%d
     )
    
  4. inside the loop, extract the file date.

    echo %%c %%a %%b - %%d
    

    And transform the month name into a number

    call :month %%a
    

    you may use the routine found in http://www.dostips.com/DtTipsStringManipulation.php

  5. inside the loop, transform the date into a number of days since today

    call :days %%c %month% %%b
    

    this is a call to a routine that computes the days using the Fliegel-Van Flandern algorithm. See this SO question for details and implementation How can I check the time stamp creation of a file in a Windows batch script?

  6. and finally, inside the loop, compare the resulting number, if it is bigger than, say, 14, add the file to the files to delete ftp script

    IF !days! GEQ 14 echo DEL %%d >>ftpdel.txt
    
  7. finish the ftp del script and execute it

    echo quit>>ftpdel.txt
    ftp -n -s:ftpdel.txt [myserver.com]
    


回答2:

It's cumbersome to implement with the built-in ftp.exe, as the very good answer by @PA. shows.

You better use some more powerful scriptable 3rd party FTP client.


For example with WinSCP FTP client, it's as trivial as:

winscp.com /ini=nul /log=delete.log /command ^
    "open ftp://username:password@ftp.example.com/" ^
    "rm /remote/path/*<14D" ^
    "exit"

See file masks with time constraints.

(I'm the author of WinSCP)