Upload timestamped file using PuTTY/SFTP file tran

2019-06-09 08:43发布

问题:

Need a help in transfer file to sftp server. We have a script with 3 stages.

Driver

ECHO off
path\file.sftp.sc.bat

Driver -file.sftp.sc.bat

@ECHO OFF

set PUTTY_HOME= LOCATION\ PUTTY
set PATH=%PUTTY_HOME%;%PATH%
REM ECHO %DOWNLOADDATA1%
set DOWNLOADDATA1="N"
IF EXIST LOCATION\"FileName.txt"  SET DOWNLOADDATA1="Y"
ECHO %DOWNLOADDATA1%
IF %DOWNLOADDATA1% =="N" goto unsucc
ECHO %DOWNLOADDATA1%
ECHO GETTING DATA FILE
psftp -password -b LOCATION\Summary_LOC_SC.ftp user name
ECHO %ERRORLEVEL%
IF %ERRORLEVEL% EQU 0 LOCATION\ Success_email.vbs
goto end
IF %ERRORLEVEL% NEQ 0 LOCATION\UNSuccess_Email.vbs
goto end
:UNSUCC
ECHO %DOWNLOADDATA1%
ECHO UNSUCCESSFUL
LOCATION\UNSuccess_FNF_Email.vbs
:END

Driver-Summary_LOC_SC.ftp

cd/fall2014
1cd LOCATION OF FILE
put "File.Txt"
quit

Now, the file name is going to be changed with date, I mean, today it will be file20141118.txt, tomorrow will be file20141119.txt.

In the above script how to implement it, so it will pull up the current file.

回答1:

If I understand the problem, you do not know how to modify the psftp script to cater for dynamic file name.

You can generate the script on the fly like:

...
ECHO GETTING DATA FILE
echo cd/fall2014 > LOCATION\Summary_LOC_SC.ftp
echo cd LOCATION OF FILE >> LOCATION\Summary_LOC_SC.ftp
echo put "File%date:~-4,4%%date:~-7,2%%date:~-10,2%.Txt" >> LOCATION\Summary_LOC_SC.ftp
echo quit >> LOCATION\Summary_LOC_SC.ftp
psftp -password -b LOCATION\Summary_LOC_SC.ftp user name
...

Note that the %date% magic above is locale specific. You may need to adjust it. Refer to How to get a UNIVERSAL Windows batch file timestamp and other similar questions here.

If you already have the renamed filename in some variable (what I understand from your comments, but do not see it in the code), it's easier, just use your variable instead of the %date%.

EDIT: Seeing your related question Batch file with current date, just use the finance variable from the answer:

echo put "%finance%" >> LOCATION\Summary_LOC_SC.ftp

Alternatively use WinSCP instead of the psftp.

It makes the code way easier thanks to:

  • its %TIMESTAMP% syntax (you won't need the awful code that generates the finance timestamped name);
  • its ability to specify commands on command-line, without need for a separate script.

Example:

...
ECHO GETTING DATA FILE
winscp.com /command ^
    "open sftp://username:password@host/" ^
    "cd /fall2014" ^
    "cd LOCATION OF FILE" ^
    "put ""File%%TIMESTAMP#yyyymmdd%%""" ^
    "exit"
...

References:
https://winscp.net/eng/docs/scripting#timestamp
https://winscp.net/eng/docs/guide_automation

(I'm the author of WinSCP)