Dynamic FTP Scripts

I seem to be getting back to basics at the moment with some of the things I’m doing – and didn’t imagine myself having to get an automated FTP update working this week…

My objective was to ‘get’ files from a remote machine using a folder pattern consisting of the date in an ‘yymmdd’ format.  I’d forgotten that script files used with ftp (ftp -s:myscript.txt) are dumb text files, and if you want to ‘get’ from a dynamic location – or dynamic filenames you need to magic something up.

My interest was sparked here, and although I found a C# FTP library on CodeProject that would clearly do the job, and would be cool to use in itself, I was more interested in using ‘old skool’ lo-tech methods to solve the problem.

I read one article that suggested using batch files to spit out the ftp script.  Excellent idea I thought – so this is what I ended up with…. (I’ve changed a few details to protect the innocent so if it doesn’t quite work it’s only due to my own typo 🙂 )

I won’t explain each bit as that would spoil the fun – but the general gist is that FTPReportsForDate is normally run without parameters and it finds files in a specific folder and renames them on the local host.  The process also does other stuff I didn’t have time to go into….

FTPReportsForDate.cmd (which accepts a parameter or gets current date if not supplied)

@echo off

echo Creating Log Folder
IF NOT EXIST C:\logs\FTP\ md c:\logs\FTP

echo Removing previous processing date
IF EXIST processingdate.txt del processingdate.txt /F

IF “%1” == “” (
 echo Getting current processing date
 cscript //NoLogo GetCurrentDate.vbs >> processingdate.txt
 echo Transferring File
 FOR /F %%f in (processingdate.txt) do CALL FTPCommand.cmd %%f

IF “%1” NEQ == “” (
 echo Transferring File
 CALL FTPCommand.cmd %1

FTPCommand.cmd  This constructs the FTP script file and does the FTP itself…

IF EXIST FTPLatestFile.txt del FTPLatestFile.txt /F

Type FTPHeader.txt >> FTPLatestFile.txt
echo cd RP%1.IN >> FTPLatestFile.txt
echo get staticfilename.fil dyn%1.fil >> FTPLatestFile.txt
echo close >> FTPLatestFile.txt
echo bye >> FTPLatestFile.txt

ftp -s:FTPLatestFile.txt >> c:\logs\ftp\transfer_%1.log

FTPHeader.txt This contains the static information used in the FTP script

lcd c:\incoming

gets current date in a yymmdd format in the event we don’t pass in a date to FTPReportsForDate.cmd

‘Simple script to output todays date in yymmdd format for FTP processing

Function pd(n, totalDigits)
 if totalDigits > len(n) then
  pd = String(totalDigits-len(n),”0″) & n
  pd = n
 end if
End Function

Wscript.echo pd(RIGHT(YEAR(date()),2),2) & pd(MONTH(date()),2) & pd(DAY(date()),2)