How to script FTP upload and download How to script FTP upload and download powershell powershell

How to script FTP upload and download


It's a reasonable idea to want to script an FTP session the way the original poster imagined, and that is the kind of thing Expect would help with. Batch files on Windows cannot do this.

But rather than doing cURL or Expect, you may find it easier to script the FTP interaction with PowerShell. It's a different model, in that you are not directly scripting the text to send to the FTP server. Instead you will use PowerShell to manipulate objects that generate the FTP dialogue for you.

Upload:

$File = "D:\Dev\somefilename.zip"$ftp = "ftp://username:password@example.com/pub/incoming/somefilename.zip""ftp url: $ftp"$webclient = New-Object System.Net.WebClient$uri = New-Object System.Uri($ftp)"Uploading $File..."$webclient.UploadFile($uri, $File)

Download:

$File = "c:\store\somefilename.zip"$ftp = "ftp://username:password@example.com/pub/outbound/somefilename.zip""ftp url: $ftp"$webclient = New-Object System.Net.WebClient$uri = New-Object System.Uri($ftp)"Downloading $File..."$webclient.DownloadFile($uri, $File)

You need PowerShell to do this. If you are not aware, PowerShell is a shell like cmd.exe which runs your .bat files. But PowerShell runs .ps1 files, and is quite a bit more powerful. PowerShell is a free add-on to Windows and will be built-in to future versions of Windows. Get it here.

Source: http://poshcode.org/1134


Create a command file with your commands.

I.e., file commands.txt:

open www.domainhere.comuser useridherepasswordhereput test.txtbye

Then run the FTP client from the command line:

ftp -s:commands.txt

Note: This will work for the Windows FTP client.


Batch files don't work that way. They don't just "type" everything - they run system commands, in this case ftp, wait for them to return, and run the next command... so in this case, the interpreter is simply waiting for ftp to exit.

If you must use the ftp command, then prepare a script file (for example, commands.txt and run ftp -s:commands.txt.

But using cURL, or a PHP/Perl/Python/whatever script may be a better idea.