Automating FTP
The Problem
I need to automate an FTP transaction. No big deal right? I need to automate my FTP transaction from inside a .net console program, then execute the same program with multiple instances that process each downloaded file.
Shell()I’m really loving this command. It’s nothing new really but for some reason or another it tends not to be common knowledge. I suppose the land of DOS and those wonderful black and white (although sometimes colorful) programs has been left slowly behind by most newer developers.
The Answer
Technically I already told you the answer to my problem, but I didn’t exactly explain it in full. Here is the code, I’ll explain it more later.
Shell(“ftp -s:ftp.script”)
Isn’t that just great!? It turns out that the normal MS-DOS FTP command already has a basic scripting control in it. So using Shell() to execute ftp, which is in my system PATH, and passing the -s:filename argument into it the ftp. The program then opens your script and uses it to answer each of the prompts it would normally give. My FTP script is very simple and here is a copy.
prompt
open ftp.myserver.com
USERNAME
PASSWORD
cd directory
mget *.txt
bye
Here is a quick breakdown of the script.
prompt: is an FTP program command which disables or enables the interactive prompt
I want this disabled so that I can automatically overwrite files, and accept file downloads.
open: standard open command, set the server IP or server name here
USERNAME: the server always asks for a username – set it here by replacing USERNAME with the real username
PASSWORD: replace it with your password
Repeat your password
cd: change directory – usage: cd /directory/to/work/in/
mget: multiple get – wildcards can be used for filename and extension
Example:
the*developer.txt would match:
thecrazydeveloper.txt, themaddeveloper.txt, and so on.
*.txt matches all files with .txt in the filename
*.* matches all files in the directory
bye: logs you out of the server
Enjoy!