There comes a time in every person’s life when they have to automate a download from an FTP server. Man, I hope that is not true.. But that time came for me recently, so I thought I’d share the script snippet to accomplish this.
Basically, I needed to set up a scheduled task that would log into an FTP server once a day and download a file. That file would subsequently be consumed by another application, but that’s not the point.
Windows comes equipped with a command-line FTP client which has option to receive a text file with instructions. Thus, the batch script for the scheduled task does the following:
- Create a text file with commands for the FTP sessions
- Calls FTP with the command file as a parameter (performs commands)
- Deletes the file with the commands
Without further ado:
@echo off set ftpServer=18.104.22.168 set ftpUser=username set ftpPass=userpassword set ftpFileName=echo %date:~10,4%%date:~4,2%%date:~7,2%.txt set localFileName=Z:\dailyDownload\file.txtrem *** login info *** echo user %ftpUser%>ftpCommands.txt echo %ftpPass%>>ftpCommands.txt rem *** commands for the server *** echo bin>> ftpCommands.txt echo get %ftpFileName% %localFileName%>> ftpCommands.txt echo quit>> ftpCommands.txt rem *** performs specified FTP operations *** ftp -n -s:ftpCommands.txt %ftpServer% rem *** remove the file with the commands *** del ftpCommands.txt rem *** unset all the variables *** set ftpServer= set ftpUser= set ftpPass= set ftpFileName= set localFileName=
So, all you have to do is modify the variables on top. In my case, I generated the file name based on the date. You can also add other commands to the get more files, or to upload files instead. More info on FTP utility can be found here.
Note on security – the script uses environment variable to store session credentials. This is obviously a risk, since environment variables are accessible to other processes on the machine. This was not a concern in my case, and I like the neatness of being able to define all the session parameters on top of the script. However, you can simply not use variables, and type in your specific credentials where the variables are used in the batch script.