While googling around the other day I noticed that lots of people are searching for a way to FTP files with VBScript. After looking for a while at the solutions to do this, it was clear that no real easy, free way of FTP uploading and downloading files was currently available. There are downloadable components that would present a programable API. But these are costly, and you'd have to install them. So seeing the need I decided to whip up a couple of functions that would preform some basic uploading and downloading.



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.

  1. Function FTPUpload(sSite, sUsername, sPassword, sLocalFile, sRemotePath)  
  2.   'This script is provided under the Creative Commons license located  
  3.   'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not  
  4.   'be used for commercial purposes with out the expressed written consent  
  5.   'of NateRice.com  
  6.  
  7.   Const OpenAsDefault = -2  
  8.   Const FailIfNotExist = 0  
  9.   Const ForReading = 1  
  10.   Const ForWriting = 2  
  11.     
  12.   Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject")  
  13.   Set oFTPScriptShell = CreateObject("WScript.Shell")  
  14.  
  15.   sRemotePath = Trim(sRemotePath)  
  16.   sLocalFile = Trim(sLocalFile)  
  17.     
  18.   '----------Path Checks---------  
  19.   'Here we willcheck the path, if it contains  
  20.   'spaces then we need to add quotes to ensure  
  21.   'it parses correctly.  
  22.   If InStr(sRemotePath, " ") > 0 Then 
  23.     If Left(sRemotePath, 1) <> """" And Right(sRemotePath, 1) <> """" Then 
  24.       sRemotePath = """" & sRemotePath & """" 
  25.     End If 
  26.   End If 
  27.     
  28.   If InStr(sLocalFile, " ") > 0 Then 
  29.     If Left(sLocalFile, 1) <> """" And Right(sLocalFile, 1) <> """" Then 
  30.       sLocalFile = """" & sLocalFile & """" 
  31.     End If 
  32.   End If 
  33.  
  34.   'Check to ensure that a remote path was  
  35.   'passed. If it's blank then pass a "\"  
  36.   If Len(sRemotePath) = 0 Then 
  37.     'Please note that no premptive checking of the  
  38.     'remote path is done. If it does not exist for some  
  39.     'reason. Unexpected results may occur.  
  40.     sRemotePath = "\" 
  41.   End If 
  42.     
  43.   'Check the local path and file to ensure  
  44.   'that either the a file that exists was  
  45.   'passed or a wildcard was passed.  
  46.   If InStr(sLocalFile, "*"Then 
  47.     If InStr(sLocalFile, " "Then 
  48.       FTPUpload = "Error: Wildcard uploads do not work if the path contains a " & _  
  49.       "space." & vbCRLF  
  50.       FTPUpload = FTPUpload & "This is a limitation of the Microsoft FTP client." 
  51.       Exit Function 
  52.     End If 
  53.   ElseIf Len(sLocalFile) = 0 Or Not oFTPScriptFSO.FileExists(sLocalFile) Then 
  54.     'nothing to upload  
  55.     FTPUpload = "Error: File Not Found." 
  56.     Exit Function 
  57.   End If 
  58.   '--------END Path Checks---------  
  59.     
  60.   'build input file for ftp command  
  61.   sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF  
  62.   sFTPScript = sFTPScript & sPassword & vbCRLF  
  63.   sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF  
  64.   sFTPScript = sFTPScript & "binary" & vbCRLF  
  65.   sFTPScript = sFTPScript & "prompt n" & vbCRLF  
  66.   sFTPScript = sFTPScript & "put " & sLocalFile & vbCRLF  
  67.   sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF  
  68.  
  69.  
  70.   sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")  
  71.   sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName  
  72.   sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName  
  73.  
  74.   'Write the input file for the ftp command  
  75.   'to a temporary file.  
  76.   Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True)  
  77.   fFTPScript.WriteLine(sFTPScript)  
  78.   fFTPScript.Close  
  79.   Set fFTPScript = Nothing    
  80.  
  81.   oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _  
  82.   " > " & sFTPResults, 0, TRUE  
  83.     
  84.   Wscript.Sleep 1000  
  85.     
  86.   'Check results of transfer.  
  87.   Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, _  
  88.   FailIfNotExist, OpenAsDefault)  
  89.   sResults = fFTPResults.ReadAll  
  90.   fFTPResults.Close  
  91.     
  92.   oFTPScriptFSO.DeleteFile(sFTPTempFile)  
  93.   oFTPScriptFSO.DeleteFile (sFTPResults)  
  94.     
  95.   If InStr(sResults, "226 Transfer complete.") > 0 Then 
  96.     FTPUpload = True 
  97.   ElseIf InStr(sResults, "File not found") > 0 Then 
  98.     FTPUpload = "Error: File Not Found" 
  99.   ElseIf InStr(sResults, "cannot log in.") > 0 Then 
  100.     FTPUpload = "Error: Login Failed." 
  101.   Else 
  102.     FTPUpload = "Error: Unknown." 
  103.   End If 
  104.  
  105.   Set oFTPScriptFSO = Nothing 
  106.   Set oFTPScriptShell = Nothing 
  107. End Function 
  108.  
  109. Function FTPDownload(sSite, sUsername, sPassword, sLocalPath, sRemotePath, _  
  110.          sRemoteFile)  
  111.   'This script is provided under the Creative Commons license located  
  112.   'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not  
  113.   'be used for commercial purposes with out the expressed written consent  
  114.   'of NateRice.com  
  115.  
  116.   Const OpenAsDefault = -2  
  117.   Const FailIfNotExist = 0  
  118.   Const ForReading = 1  
  119.   Const ForWriting = 2  
  120.     
  121.   Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject")  
  122.   Set oFTPScriptShell = CreateObject("WScript.Shell")  
  123.  
  124.   sRemotePath = Trim(sRemotePath)  
  125.   sLocalPath = Trim(sLocalPath)  
  126.     
  127.   '----------Path Checks---------  
  128.   'Here we will check the remote path, if it contains  
  129.   'spaces then we need to add quotes to ensure  
  130.   'it parses correctly.  
  131.   If InStr(sRemotePath, " ") > 0 Then 
  132.     If Left(sRemotePath, 1) <> """" And Right(sRemotePath, 1) <> """" Then 
  133.       sRemotePath = """" & sRemotePath & """" 
  134.     End If 
  135.   End If 
  136.     
  137.   'Check to ensure that a remote path was  
  138.   'passed. If it's blank then pass a "\"  
  139.   If Len(sRemotePath) = 0 Then 
  140.     'Please note that no premptive checking of the  
  141.     'remote path is done. If it does not exist for some  
  142.     'reason. Unexpected results may occur.  
  143.     sRemotePath = "\" 
  144.   End If 
  145.     
  146.   'If the local path was blank. Pass the current  
  147.   'working direcory.  
  148.   If Len(sLocalPath) = 0 Then 
  149.     sLocalpath = oFTPScriptShell.CurrentDirectory  
  150.   End If 
  151.     
  152.   If Not oFTPScriptFSO.FolderExists(sLocalPath) Then 
  153.     'destination not found  
  154.     FTPDownload = "Error: Local Folder Not Found." 
  155.     Exit Function 
  156.   End If 
  157.     
  158.   sOriginalWorkingDirectory = oFTPScriptShell.CurrentDirectory  
  159.   oFTPScriptShell.CurrentDirectory = sLocalPath  
  160.   '--------END Path Checks---------  
  161.     
  162.   'build input file for ftp command  
  163.   sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF  
  164.   sFTPScript = sFTPScript & sPassword & vbCRLF  
  165.   sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF  
  166.   sFTPScript = sFTPScript & "binary" & vbCRLF  
  167.   sFTPScript = sFTPScript & "prompt n" & vbCRLF  
  168.   sFTPScript = sFTPScript & "mget " & sRemoteFile & vbCRLF  
  169.   sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF  
  170.  
  171.  
  172.   sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")  
  173.   sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName  
  174.   sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName  
  175.  
  176.   'Write the input file for the ftp command  
  177.   'to a temporary file.  
  178.   Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True)  
  179.   fFTPScript.WriteLine(sFTPScript)  
  180.   fFTPScript.Close  
  181.   Set fFTPScript = Nothing    
  182.  
  183.   oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _  
  184.   " > " & sFTPResults, 0, TRUE  
  185.     
  186.   Wscript.Sleep 1000  
  187.     
  188.   'Check results of transfer.  
  189.   Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, _  
  190.                     FailIfNotExist, OpenAsDefault)  
  191.   sResults = fFTPResults.ReadAll  
  192.   fFTPResults.Close  
  193.     
  194.   'oFTPScriptFSO.DeleteFile(sFTPTempFile)  
  195.   'oFTPScriptFSO.DeleteFile (sFTPResults)  
  196.     
  197.   If InStr(sResults, "226 Transfer complete.") > 0 Then 
  198.     FTPDownload = True 
  199.   ElseIf InStr(sResults, "File not found") > 0 Then 
  200.     FTPDownload = "Error: File Not Found" 
  201.   ElseIf InStr(sResults, "cannot log in.") > 0 Then 
  202.     FTPDownload = "Error: Login Failed." 
  203.   Else 
  204.     FTPDownload = "Error: Unknown." 
  205.   End If 
  206.     
  207.   Set oFTPScriptFSO = Nothing 
  208.   Set oFTPScriptShell = Nothing 
  209. End Function 

******************************************************

  1. 'Option Explicit  
  2. 'const progname="FTP upload script by Richard Finegold"  
  3. 'const url = "ftp://ftp.myftpsite.com"  
  4. 'const rdir = "mydir"  
  5. 'const user = "anonymous"  
  6. 'const pass = "myname@mymailsite.com"  
  7.  
  8. 'This is an example of ftp'ing without calling the external "FTP" command  
  9. 'It uses InetCtrls.Inet.1 instead  
  10. 'Included is a "hint" for simple downloading  
  11.  
  12. 'Sources:  
  13. 'http://msdn.microsoft.com/library/partbook/ipwvb5/loggingontoftpserver.htm  
  14. 'http://msdn.microsoft.com/library/partbook/egvb6/addinginternettransfercontrol.htm  
  15. 'http://cwashington.netreach.net/ - search on "ftp" - inspiration only!  
  16.  
  17. 'Insist on arguments  
  18. dim objArgs  
  19. Set objArgs = Wscript.Arguments  
  20. If 0=objArgs.Count Then 
  21.    MsgBox "No files selected for operation!", vbOkOnly + vbCritical, progname  
  22.    WScript.Quit  
  23. End If 
  24.  
  25.  
  26. 'Force console mode - csforce.vbs (with some reorganization for efficiency)  
  27. dim i  
  28. if right(ucase(wscript.FullName),11)="WSCRIPT.EXE" then  
  29.   dim args, y  
  30.   For i = 0 to objArgs.Count - 1  
  31.     args = args + " " + objArgs(i)  
  32.   Next 
  33.   Set y = WScript.CreateObject("WScript.Shell")  
  34.   y.Run "cscript.exe " & wscript.ScriptFullName + " " + args, 1  
  35.   wscript.quit  
  36. end if  
  37.  
  38.  
  39. 'Do actual work  
  40. dim fso, ftpo  
  41. set fso = WScript.CreateObject("Scripting.FileSystemObject")  
  42. set ftpo = WScript.CreateObject("InetCtls.Inet.1")     'Msinet.ocx  
  43. ftpo.URL = url  
  44. ftpo.UserName = user  
  45. ftpo.Password = pass  
  46. WScript.Echo "Connecting..." 
  47. ftpo.Execute , "CD " & rdir  
  48. do  
  49. '     WScript.Echo "."  
  50.      WScript.Sleep 100     'This can take a while loop while ftpo.StillExecuting  
  51.  
  52.  
  53. for i = 0 to objArgs.Count - 1  
  54.      dim sLFile  
  55.      sLFile = objArgs(i)  
  56.  
  57.      if (fso.FileExists(sLFile)) then  
  58.           WScript.Echo "Uploading " & sLFile & " as " & FSO.GetFileName(sLFile) & " " 
  59.           ftpo.Execute , "Put " & sLFile & " " & FSO.GetFileName(sLFile)  
  60.           'ftpo.Execute , "Get " & sRemoteFile & " C:\" & sLFile  
  61.           do  
  62.           'WScript.Echo "."  
  63.                WScript.Sleep 100     'This can take a while  
  64.           loop while ftpo.StillExecuting  
  65.      else  
  66.           MsgBox Chr(34) & sLFile & Chr(34) & " does not exist!", _  
  67.            vbOkOnly, progname  
  68.      end if  
  69. next  
  70. WScript.Echo "Closing" 
  71. ftpo.Execute , "Close" 
  72. WScript.Echo "Done!" 
此文章由 flyinweb 于 2010-03-13 10:54:27 编辑

本日志由 flyinweb 于 2010-03-13 10:46:47 发表,目前已经被浏览 4121 次,评论 0 次;

作者添加了以下标签: FTPVBS

引用通告:http://www.517sou.net/Article/412/Trackback.ashx

评论订阅:http://www.517sou.net/Article/412/Feeds.ashx

评论列表

    暂时没有评论
(必填)
(必填,不会被公开)