FTP Upload and FTP Download with VBScript
Pretty straight forward, you have to supply the credentials to connect to the machine, the IP address or DNS name for the machine and then the source and destination locations. Example of syntax:
| Wscript.Echo FTPDownload("192.168.1.1", "domain\user", "password", "C:\", "\", "*") |
When using the download function, if you don't specify a location it will default to the working directory of the script. If for some reason there is a problem transferring the file the functions will return the error message. If they are successful, they will return "true".
Update 11-30-2007: I just made some corrections to this per the suggestions of some emails and comments I received. I retested this script, since it's been quite some time since I've had the chance to use it, and it's working like a charm. Please continue to report any issues you might have and thank you for your feedback.
**Please note that you are obviously passing credentials in plain text in this script and it presents a potential security risk.**
| Function FTPUpload(sSite, sUsername, sPassword, sLocalFile, sRemotePath) 'This script is provided under the Creative Commons license located 'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not 'be used for commercial purposes with out the expressed written consent 'of NateRice.com Const OpenAsDefault = -2 Const FailIfNotExist = 0 Const ForReading = 1 Const ForWriting = 2 Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject") Set oFTPScriptShell = CreateObject("WScript.Shell") sRemotePath = Trim(sRemotePath) sLocalFile = Trim(sLocalFile) '----------Path Checks--------- 'Here we willcheck the path, if it contains 'spaces then we need to add quotes to ensure 'it parses correctly. If InStr(sRemotePath, " ") > 0 Then If Left(sRemotePath, 1) <> """" And Right(sRemotePath, 1) <> """" Then sRemotePath = """" & sRemotePath & """" End If End If If InStr(sLocalFile, " ") > 0 Then If Left(sLocalFile, 1) <> """" And Right(sLocalFile, 1) <> """" Then sLocalFile = """" & sLocalFile & """" End If End If 'Check to ensure that a remote path was 'passed. If it's blank then pass a "\" If Len(sRemotePath) = 0 Then 'Please note that no premptive checking of the 'remote path is done. If it does not exist for some 'reason. Unexpected results may occur. sRemotePath = "\" End If 'Check the local path and file to ensure 'that either the a file that exists was 'passed or a wildcard was passed. If InStr(sLocalFile, "*") Then If InStr(sLocalFile, " ") Then FTPUpload = "Error: Wildcard uploads do not work if the path contains a " & _ "space." & vbCRLF FTPUpload = FTPUpload & "This is a limitation of the Microsoft FTP client." Exit Function End If ElseIf Len(sLocalFile) = 0 Or Not oFTPScriptFSO.FileExists(sLocalFile) Then 'nothing to upload FTPUpload = "Error: File Not Found." Exit Function End If '--------END Path Checks--------- 'build input file for ftp command sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF sFTPScript = sFTPScript & sPassword & vbCRLF sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF sFTPScript = sFTPScript & "binary" & vbCRLF sFTPScript = sFTPScript & "prompt n" & vbCRLF sFTPScript = sFTPScript & "put " & sLocalFile & vbCRLF sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%") sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName 'Write the input file for the ftp command 'to a temporary file. Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True) fFTPScript.WriteLine(sFTPScript) fFTPScript.Close Set fFTPScript = Nothing oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _ " > " & sFTPResults, 0, TRUE Wscript.Sleep 1000 'Check results of transfer. Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, _ FailIfNotExist, OpenAsDefault) sResults = fFTPResults.ReadAll fFTPResults.Close oFTPScriptFSO.DeleteFile(sFTPTempFile) oFTPScriptFSO.DeleteFile (sFTPResults) If InStr(sResults, "226 Transfer complete.") > 0 Then FTPUpload = True ElseIf InStr(sResults, "File not found") > 0 Then FTPUpload = "Error: File Not Found" ElseIf InStr(sResults, "cannot log in.") > 0 Then FTPUpload = "Error: Login Failed." Else FTPUpload = "Error: Unknown." End If Set oFTPScriptFSO = Nothing Set oFTPScriptShell = Nothing End Function Function FTPDownload(sSite, sUsername, sPassword, sLocalPath, sRemotePath, _ sRemoteFile) 'This script is provided under the Creative Commons license located 'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not 'be used for commercial purposes with out the expressed written consent 'of NateRice.com Const OpenAsDefault = -2 Const FailIfNotExist = 0 Const ForReading = 1 Const ForWriting = 2 Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject") Set oFTPScriptShell = CreateObject("WScript.Shell") sRemotePath = Trim(sRemotePath) sLocalPath = Trim(sLocalPath) '----------Path Checks--------- 'Here we will check the remote path, if it contains 'spaces then we need to add quotes to ensure 'it parses correctly. If InStr(sRemotePath, " ") > 0 Then If Left(sRemotePath, 1) <> """" And Right(sRemotePath, 1) <> """" Then sRemotePath = """" & sRemotePath & """" End If End If 'Check to ensure that a remote path was 'passed. If it's blank then pass a "\" If Len(sRemotePath) = 0 Then 'Please note that no premptive checking of the 'remote path is done. If it does not exist for some 'reason. Unexpected results may occur. sRemotePath = "\" End If 'If the local path was blank. Pass the current 'working direcory. If Len(sLocalPath) = 0 Then sLocalpath = oFTPScriptShell.CurrentDirectory End If If Not oFTPScriptFSO.FolderExists(sLocalPath) Then 'destination not found FTPDownload = "Error: Local Folder Not Found." Exit Function End If sOriginalWorkingDirectory = oFTPScriptShell.CurrentDirectory oFTPScriptShell.CurrentDirectory = sLocalPath '--------END Path Checks--------- 'build input file for ftp command sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF sFTPScript = sFTPScript & sPassword & vbCRLF sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF sFTPScript = sFTPScript & "binary" & vbCRLF sFTPScript = sFTPScript & "prompt n" & vbCRLF sFTPScript = sFTPScript & "mget " & sRemoteFile & vbCRLF sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%") sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName 'Write the input file for the ftp command 'to a temporary file. Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True) fFTPScript.WriteLine(sFTPScript) fFTPScript.Close Set fFTPScript = Nothing oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _ " > " & sFTPResults, 0, TRUE Wscript.Sleep 1000 'Check results of transfer. Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, _ FailIfNotExist, OpenAsDefault) sResults = fFTPResults.ReadAll fFTPResults.Close 'oFTPScriptFSO.DeleteFile(sFTPTempFile) 'oFTPScriptFSO.DeleteFile (sFTPResults) If InStr(sResults, "226 Transfer complete.") > 0 Then FTPDownload = True ElseIf InStr(sResults, "File not found") > 0 Then FTPDownload = "Error: File Not Found" ElseIf InStr(sResults, "cannot log in.") > 0 Then FTPDownload = "Error: Login Failed." Else FTPDownload = "Error: Unknown." End If Set oFTPScriptFSO = Nothing Set oFTPScriptShell = Nothing End Function |
| Send this to: |

Comments
Pavel said...
Its cool code! Thanks
11/20/2007 12:16:29 AM
Bryan Gilsenan said...
Hi there,
This gives me an error saying...Object required Wscript..I tried commemting out the piece which refers to Wscript but it doesn't work, any thoughts? Thanks.
11/30/2007 6:06:36 AM
Jan+Batka said...
Hi,
Just in case you would like to Up\Down-load a list of files: sep. by ";".
Dim sFileArr, i
If InStr(sRemoteFile, ";") Then
sFTPScript = sFTPScript & "USER " & sUsername & vbCrLf
sFTPScript = sFTPScript & sPassword & vbCrLf
sFTPScript = sFTPScript & "cd " & sRemotePath & vbCrLf
sFTPScript = sFTPScript & "binary" & vbCrLf
sFTPScript = sFTPScript & "prompt n" & vbCrLf
sFileArr = Split(sRemoteFile, ";")
For i = 0 To UBound(sFileArr)
sFTPScript = sFTPScript & "mget " & Trim(sFileArr(i)) & vbCrLf
Next
sFTPScript = sFTPScript & "quit" & vbCrLf & "quit" & vbCrLf & "quit" & vbCrLf
Else
sFTPScript = sFTPScript & "USER " & sUsername & vbCrLf
sFTPScript = sFTPScript & sPassword & vbCrLf
sFTPScript = sFTPScript & "cd " & sRemotePath & vbCrLf
sFTPScript = sFTPScript & "binary" & vbCrLf
sFTPScript = sFTPScript & "prompt n" & vbCrLf
sFTPScript = sFTPScript & "mget " & sRemoteFile & vbCrLf
sFTPScript = sFTPScript & "quit" & vbCrLf & "quit" & vbCrLf & "quit" & vbCrLf
End If
12/6/2007 7:32:59 AM
Guru said...
Great work Kudos... Functions are just Charm to work with.. Salutations...
3/18/2008 1:15:10 AM
candyman said...
hi, i'm learning vbs...and i'm trying to understant...sometime works, sometimes don't.
i don't figure out where to modify with my ftp, user and pass...i know it's lame...but i need help.
4/20/2008 3:19:07 PM
said...
A good code ! I like it !
Can you show me the code about Upload a file by a dll ?
6/10/2008 1:03:43 AM
said...
Very good. Works as expected and is very nicely coded.
7/1/2008 4:21:14 AM
said...
This article helped me solve a crisis. Here is the code that I wrote. A service rep enters their 4-digit employee ID number to download all the files from the FTP server that have their ID number as the first four digits of the file name.
-------------------
strUserIn = InputBox("Enter LSR ID Below","LSR File Download Utility")
if len(strUserIn) = 4 then
strUserIn = strUserIn & "*"
else
msgbox "Please enter a valid LSR ID number!",0,"LSR File Download Utility"
wscript.quit
end if
Set fs = CreateObject("Scripting.FileSystemObject")
strFileName = fs.BuildPath(Wscript.ScriptFullName & "\..", "get_lsr_files.txt")
strFileName = fs.GetAbsolutePathName(strFileName)
text_string = "open ftp.molottery.com" & chr(13) & chr(10) _
& "anonymous" & chr(13) & chr(10) _
& "password" & chr(13) & chr(10) _
& "cd IntraRpt/Sales/LSR" & chr(13) & chr(10) _
& "prompt" & chr(13) & chr(10) _
& "mget " & strUserIn & chr(13) & chr(10) _
& "quit"
Set ts = fs.OpenTextFile(strFileName, 2, True)
ts.WriteLine text_string
strFileName = fs.BuildPath(Wscript.ScriptFullName & "\..", "cl.bat")
strFileName = fs.GetAbsolutePathName(strFileName)
text_string = "set wd=%cd%" & chr(13) & chr(10) _
& "cd=""%userprofile%""\desktop\Reports" & chr(13) & chr(10) _
& """%systemroot%""\system32\ftp.exe -s:""%wd%""\get_lsr_files.txt" & chr(13) & chr(10) _
& "cd ""%wd%""" & chr(13) & chr(10) _
& "del get_lsr_files.txt" & chr(13) & chr(10) _
& "del cl.bat"
Set ts = fs.OpenTextFile(strFileName, 2, True)
ts.WriteLine text_string
ts.Close
Set objShell = CreateObject("WScript.Shell")
objShell.Run "cl.bat", , True
7/11/2008 10:33:01 AM
said...
Great, I''ve been tearing my hair out over .bat files for the last six hours. This worked first go.
8/15/2008 3:07:53 AM
said...
How do you call the FTPUpload function from a batch file or command prompt? I have tried several ways with the parameters and have been unsuccessful...
9/4/2008 2:31:49 PM
said...
Did not work. FTPUpload function always failed with ''invalid parameter'' error even though it was being passed 4 strings.
10/24/2008 4:09:29 PM
said...
Hi, I used this script in a loop and it runs 26 times works very well thanks.
However I wondered what I need to do to a message popping up after the script runs as I would like to sheduale it and leave it.
thanks
David.
11/20/2008 7:06:08 AM
said...
Hey David,
Run the script with cscript.exe instead of wscript.exe.
-Nate
11/24/2008 12:16:20 AM
said...
Nate, the "226 Transfer complete" string is not consistent across all ftp servers. Testing for presence of "226" should suffice.
-Vince
12/11/2008 5:14:44 PM
said...
I''ve tried to use FTPUpload function but always error message is unknown. I''ve tried to pass the parameters as follows:
FTPUpload("MyIP", "ftp.company.com\MyUserID", "Mypassword", "LocalPath", "ftp.company.com\Myfolder").
Where I make a mistake?
12/12/2008 9:21:04 AM
said...
Need something like this that can check on the FTP host in an unknown directory/folder name and then download the entire folder if and only if a specific file "eot.txt" is present in that folder. If not, leave the folder there.
Please advise.
12/12/2008 10:32:20 AM
said...
For those who have never used VBS, ever, here''s what I did to get this working:
1. copy paste code into something.vbs
2. below code copy / paste Wscript.echo line
3. triple check to make sure logins and paths are accurate
4. open CMD window and do: wscript something.vbs
If you get an "Error: Unknown" window something is wrong with your credentials.
3/9/2009 2:33:19 PM
said...
I''m trying to make a version for passive mode ftp, but it''s tough. the command for passive mode is ''quote pasv''. Like this the FTP server replies with the correct ''227 entering passive mode...'' but i don''t know how to use the given port for the next transaction.
4/3/2009 3:49:58 AM
said...
Thanks bro Ive been wrestling with this for a few hours trying to pipe the FTP output to a logfile, it was the %comspec% /c that made it work!
6/3/2009 2:11:27 PM
said...
The download function works, when i use the upload function it starts like 20 time and errors each time and clues
6/23/2009 2:39:28 AM
said...
I really can''t think of any more ways to modify this, but the output i''m getting it either Error:Unknown (If I try to use c:\ftp\*) Cannot find file (c:\ftp\)
or If I try c:\ftp\item.txt the output I get is
-1
Any which way you slice it, I had to remove the "*" at the end of the Wscript.Echo line. Here''s what I have:
Wscript.Echo FTPUpload("255.0.0.0", "ftpuser", "ftppw", "c:\ftp\item.txt", "/cplus/from/content")
8/19/2009 10:19:33 AM
said...
Omg, this is awsome code, :clap: :clap:
9/3/2009 11:00:07 AM
said...
Excellent! Works like a charm for backing up the files on my web server.
how do I upload though?
9/10/2009 1:01:07 PM
said...
How would I go about (just don''t know the commands) deleting the files i just downloaded?
10/8/2009 10:07:32 AM
said...
I tried this but I cannot make it work, just the .Run line, is not giving any error but is not doing anything, is not generating the result file and is not uploading the file I need to FTP.
I thought it might be a permission issue but, if I take the line I''m creating on the vbs file and paste it directly to a cmd window it will work.
Any ideas?
1/18/2010 8:38:41 AM
said...
Good script.
You may want to look at this script also.
http://www.biterscripting.com/SS_FTPUpload.html
It uploads an entire directory (including subfolders and files within it). It creates subfolders as necessary.
2/7/2010 9:02:02 AM
said...
I like the code, however I am having 2 issues, 1. It is uploading to my remote directory, however the file is blank and 2. It is hanging on the command line and spinning its wheels. Thanks for any help you can provide
3/11/2010 10:10:10 AM
said...
I am new to the script and I wonder how it works. I am just trying to test this scipt realtime in my machine.
Could you please help me how/where should i enter my ftp details, password and remote location path in the script so that i can exceute it?
can you please explain me the procedure how to implement it? i am very curious to know.
7/19/2010 5:04:25 AM
said...
YOU ROCK! Thanks for the script.
8/9/2010 1:58:15 PM
said...
This part of the script does not work on Windows 7:
oFTPScriptShell.Run "%comspec% /c FTP -n -i -s:" & sFTPTempFile & " " & sSite & _
" > " & sFTPResults'', 0, TRUE
9/30/2010 12:24:40 AM
said...
Hello,
As I''m beginner, I have some difficulties.
Can someone please help me.?
I need to make a copy of a file in remote directory on a remote server.by SFTP.
I saw The upload function in the sample, but I don''t really understand everything.
''build input file for ftp command
sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF
sFTPScript = sFTPScript & sPassword & vbCRLF
sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF
sFTPScript = sFTPScript & "binary" & vbCRLF
sFTPScript = sFTPScript & "prompt n" & vbCRLF
sFTPScript = sFTPScript & "put " & sLocalFile & vbCRLF
sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF
sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")
also this :
oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _
" > " & sFTPResults, 0, TRUE
Thank you;
4/8/2011 6:31:59 AM
said...
I continue to get an unknown error message when I run the command as follows? Wheh this error occurs is is just because the user name or password is incorrect? Or can it be related to the other variables being passed?
Wscript.Echo FTPDownload("XX.XX.XXX.XX", "ctemXXX", "areaXX", "C:\", "/", "ftp.log")
4/17/2011 11:34:26 AM
said...
Thank you for taking the time to talk about this, I feel fervently about it and I enjoy learning about this topic. Please, as you gain data, please add to this blog with more information. I have found it extremely useful.
5/19/2011 6:13:08 PM
said...
Hey nate,
Nice job. haven''t tested it yet but confident it works and will do the job. doen''t look like theres a progress bar, just a thought, can we parse the current size of the file and compare that to the actual file size and get some indicator?
5/20/2011 2:47:41 PM
said...
Thank you for providing good information
6/1/2011 11:50:00 PM
said...
Nice script. Thanks !
I found that the Windows firewall on Vista/7 can get in the road of this. The Windows FTP client uses active mode meaning that the FTP server attempts to make a connection back to the client for the data transfer. The Win 7 advanced firewall blocks it.
Unfortunately the Windows FTP.EXE cannot be made to run in PASV mode, so you need to either disable the firewall or add a program exception. The exception can be added programatically using this command:
netsh advfirewall firewall add rule name="Permit FTP Client" dir=in action=allow enable=yes profile=any program=%SystemRoot%\System32\ftp.exe
Steve
7/7/2011 9:02:13 PM
said...
Good share,you article very great, very usefull for us…thank you
8/23/2011 12:14:10 AM
said...
thank you, worked great
9/22/2011 12:03:48 PM
said...
Nice script but I get the message "-1". Has anyone the same problem?
11/10/2011 1:27:25 AM
said...
Thank you... this greatly helped me!
1/20/2012 11:24:46 AM
said...
Nice script! It was very helpful to me!
1/25/2012 1:23:45 AM
said...
When I execute the code I get nothing - no errors generated (it does if I specify an invalid file name etc).
I''m running II6 on a Windows 2003 server. Any ideas would be greatly appreciated.
Darren.
2/16/2012 3:03:43 AM
said...
Hello, i am getting the error : Unknown when running this script :S could anyone help me whats wrong with that
2/17/2012 12:31:19 PM
said...
Hello Brother, Very nice script. I am new to VBS. I want to copy newly added files (or) files added on today to ftp server. please help me out.
2/27/2012 9:21:46 PM
said...
Hi, very helpful code, but i want to get files, added on particular date to ftp server. Please guide us.
2/28/2012 8:37:10 PM
said...
What can I do if I use another port than 20,21 ???
3/12/2012 1:51:41 PM
said...
Hi There,
Great script, but with the FTP input file what if there are spaces in the File Paths, how do we automatically include "quotes" ie..
Put "C:\FTP Folder\My Test Document.Doc"
As when it FTP''s the file to the remote FTP server, it works fine if there are no spaces? But fails if there are spaces in the path.
Thanks!!
3/29/2012 11:07:39 PM
said...
Great code, learnt a lot. Thanks
4/11/2012 3:44:05 AM
said...
I made the following changes to the upload function to allow for a different port number.
Line 1:
Function FTPUpload(sSite, sPort, sUsername, sPassword, sLocalFile, sRemotePath)
Line 60:
sFTPScript = sFTPScript & "open" & " " & sSite & " " & sPort & vbCRLF
Line 80:
oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & " > " & sFTPResults, 0, TRUE
Similar changes can be done for the Download portion of things.
5/4/2012 12:24:36 PM
said...
I got the download script to work, however, I''m getting a dialog box with nothing but -1 in it. I noticed someone else was having this happen as well. I only need this script to download a specific file from a specific server who names/location will never change...so I tried taking out all the checks since alot of these result in a dialog box appearing. Now when I run the script, I get a blank dialog box...the file still downloads right though. How can I get rid of this dialog box?
5/28/2012 8:06:53 AM
said...
If you are getting no feedback or the Error: Unknown message it may be because your firewall or antivirus is blocking Active FTP, and you have to configure this program to run in Passive FTP. I''m not yet sure how to accomplish this. There is a posting that claims you can run Windows ftp.exe in passive mode: http://myonecent.wordpress.com/2010/11/14/how-to-use-windows-command-line-ftp-exe-to-use-passive-mode-data-transfer/.
7/19/2012 6:26:21 AM
said...
I don''t know if this is a function of the OS, Server 2008 R2, I''m using, but the FileUpload function was giving me trouble until I changed the order of the Path Checks and File checks.
Since the Path check for spaces adds quotes, it causes oFTPScriptFSO.FileExists(sLocalFile) to return false.
Simply moving lines 43 through 57 above the first path check at line 19 fixed the issue.
8/16/2012 6:03:04 AM