Search code examples
batch-filecmdautomationputtypscp

How to download last modified file from remote server to local using PuTTY batch file


I have a query regarding the putty batch file. This is my .bat file:

C:
cd Program Files (x86)\PuTTY
pscp -2 -v -pw khair1 -sftp  abc@****.na.ab.com:/qwe/asd/tryu/*.csv.zip P:\Projects\abc\Test_bacth\Batch_download
pause"

So every week I have to give file name like /qwe/asd/tryu/**04242016***.csv.zip

How can I dynamically get all the file which is last modified.


Solution

  • You can use these commands to generate the today's stamp:

    for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set LDT=%%j
    set STAMP=%LDT:~0,4%%LDT:~4,2%%LDT:~6,2%
    echo %STAMP%
    

    See How do I get current datetime on the Windows command line, in a suitable format for using in a filename?


    Or use some more powerful SFTP/SCP client.

    For example with WinSCP scripting, you can do:

    "C:\Program Files (x86)\WinSCP\WinSCP.com" /command ^
        "open sftp://abc:password@****.na.ab.com/ -hostkey=""ssh-rsa 2048 xxxxxxxxxxx...=""" ^
        "get /qwe/asd/tryu/%%TIMESTAMP#yyyymmdd%%*.csv.zip ""P:\Projects\abc\Test_bacth\Batch download\""" ^
        "exit"
    

    See documentation for the %TIMESTAMP% syntax.


    If the timestamp is actually not today's, instead of specifying the timestamp, just download the latest file for each pattern/mask.

    It's easy with WinSCP, just use the -latest switch:

    "C:\Program Files (x86)\WinSCP\WinSCP.com" /command ^
        "open sftp://abc:password@****.na.ab.com/ -hostkey=""ssh-rsa 2048 xxxxxxxxxxx...=""" ^
        "lcd ""P:\Projects\abc\Test_bacth\Batch download""" ^
        "cd /qwe/asd/tryu" ^
        "get -latest *_cpg_aob_detail.csv.zip" ^
        "get -latest *_fmcg_cob_detail.csv.zip" ^
        ...
        "exit"
    

    See also other options for downloading the most recent files.

    (I'm the author of WinSCP)