vbscript to grab newest file on ftp site - vbscript

I need to comeup with a vbscript to grab a file from an ftp site where the file name is in the form "vendor(date)(date)(random#).zip" . These files are updated daily so I need a regex or way to select the newest file on the server and download it. I know how to handle this on the local file system, but I don't know how to determine which file to get on a remote ftp server.

Funny you posted this as I just recently had to knock out a script to do almost exactly word for word what you're asking for. Basically, all you really need to do is to have your script create an FTP command file, then call it.
Use your method of choice to create a string to hold the date in whatever format you are looking for, I called it strDate and in my case it ended up being this syntax: headerinfo.13September10 Where headerinfo is a standard file header with a number attached to it.
Write out an FTP command file:
Dim objOutStream
Set objOutStream = objFSO.OpenTextFile(strCommandFile, ForWriting, True, TristateFalse)
With objOutStream
.WriteLine "USER xxxxxx" ' USERNAME
.WriteLine "xxxxxxftp" ' Password
.WriteLine "binary"
.WriteLine "prompt n"
.WriteLine "lcd " & strNetmonData ' FOLDER I'm changing into
.WriteLine "mget *." & strDate ' Get all files with today's date in it
.WriteLine "bye"
.Close
End With
Then later in your script you just call it:
WSHShell.Run "%comspec% /c FTP -n -s:" & strCommandFile & " " & strSite, 0, True
Where strSite is the IP or name of the site you are trying to connect to.

The following code will help you to get the latest file name from ftp server after which you can download it.
Const ForWriting = 2
Dim objOutStream, objjFSO, objShell
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutStream = objFSO.OpenTextFile("C:\temp\temp\empty.txt", ForWriting,True)
With objOutStream
.WriteLine sUsername ' USERNAME
.WriteLine sPassword ' Password
.WriteLine "cd /"& sRemotePath' FOLDER I'm changing into
.WriteLine "ls -rt tmp/listing.txt"
.WriteLine "quit"
.Close
End With
Set objShell = CreateObject("WScript.Shell")
objShell.Run "%Comspec% /c FTP -i -s:" & "C:\temp\temp\empty.txt" & " " & sSite
wait(2)
Set strCommand = objShell.Exec ("%Comspec% /c head -1 tmp\listing.txt")
Set objStdOut = strCommand.StdOut
strFilename = objStdOut.ReadLine

Related

VBS Script, CopyFile File

I am new to vbs scripting, I have been working on a script to create a directory with user input. Then the script copies a specific file into the newly created directory. I can't seem to get the file into the newly created directory. any help would be great!!
dim UserName
Do
UserName = InputBox ("Enter Client Name with no spaces IE: lastname_firstname")
If UserName = "" then
Msgbox "No Username entered"
end if
Loop Until UserName <> ""
MsgBox "Please click OK to continue"
MsgBox "Check \\server\path\share\ for NEW client folder"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "cmd /c mkdir \\server\path\share\" & UserName
sPath = "\\server\path\share\"
Set oShell = CreateObject("WScript.Shell")
oShell.Run "explorer /n," & sPath & UserName, 1, False
Set oShell = Nothing
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("\\server\path\share\some_type_file.docx") Then
filesys.CopyFile "\\server\path\share\some_type_file.docx", "\\server\path\share\" <<COPY FILE INTO NEWLY CREATED DIRECTORY "UserName">>
End If
Try to change the last line to this
filesys.CopyFile "\\server\path\share\some_type_file.docx", "\\server\path\share\" & UserName & "\"

FTP:Upload file to FTP and verify

I am using VBS to
Upload a file to FTP
Verify the upload process
I am using the method which creates a text file, fills it with the appropriate command and then execute it using ftp.exe in windows.
FTPCommand = "%systemroot%\System32\ftp.exe -s:session.txt"
FTPCommand = objshell.ExpandEnvironmentStrings(FTPCommand)
objshell.Run FTPCommand,, vbTrue
fso.DeleteFile "session.txt", vbTrue
Part 1 is done using this code:
Set SessionFile = fso.OpenTextFile("session.txt", 2, vbTrue)
With SessionFile
.WriteLine "open abcd.com"
.WriteLine "username"
.WriteLine "pwd"
.WriteLine "cd /Test/Test1"
.WriteLine "put """ & File.Path & """"
.WriteLine "quit"
.Close
End With
FTPCommand = "%systemroot%\System32\ftp.exe -s:session.txt"
FTPCommand = objshell.ExpandEnvironmentStrings(FTPCommand)
objshell.Run FTPCommand,, vbTrue
fso.DeleteFile "session.txt", vbTrue
And Part 2 is done using this code:
Set SessionFile = fso.OpenTextFile("session.txt", 2, vbTrue)
With SessionFile
.WriteLine "open abcd.com"
.WriteLine "username"
.WriteLine "pwd"
.WriteLine "cd /Test/Test1"
.WriteLine "ls"
.WriteLine "close"
.WriteLine "bye"
.Close
End With
FTPCommand = "%systemroot%\System32\ftp.exe -s:session.txt"
FTPCommand = objshell.ExpandEnvironmentStrings(FTPCommand)
set ObjExec=objshell.exec(FTPCommand)
DO WHILE ObjExec.status=0 : wscript.sleep 50 : LOOP
StrTemp=ObjExec.stdout.readall
IF instr(1,StrTemp,File.Name,1)<>0 THEN
AlertMessage = AlertMessage & vbTab & "STATUS: UPLOAD SUCCESSFUL" & vbCrLf & vbCrLf
ELSE
AlertMessage = AlertMessage & vbTab & "STATUS: UPLOAD FAILED" & vbCrLf & vbCrLf
END IF
fso.DeleteFile "session.txt", vbTrue
The problem is that (in part 2 code) the code after
DO WHILE ObjExec.status=0 : wscript.sleep 50 : LOOP
never returns.So the file gets uploaded but the code to check the status never returns.
The session.txt file does not get delete and when I execute the command
%systemroot%\System32\ftp.exe -s:session.txt
manually it indeed shows me the list of files (because of ls command).
I have 3 questions:
Why it does not return. Where to start debugging from?
Is there anyway I can upload the file and check its status(maybe by
the error code returned by the ftp command after the "put" command).
Is there is an incorrect directory specified in the code to upload
file, the cd command fails and it incorrectly "puts" the file in the
root folder. same goes for the code checking the file upload. So
even if the directory specified in wrong, the program returns it as
successful
Edit 1:
I tried it using
.WriteLine "cd /Test"
and it worked. Is that directory switching (two folders deep)causing the problem ?
Edit 2:
I ran the ls command manually and it ran fine. The output is:
226 Transfer complete.
ftp: 586493 bytes received in 4.28Seconds 137.00Kbytes/sec.
Is 586493 bytes too much for this ?
I believe the problem may be:
1)The large no of files returned by LS command.
2)The directory structure I am accessing.
Edit:3
From this microsoft website it looks like the above point 1 is the culprit:
A console application's StdOut and StdErr streams share the same
internal 4KB buffer. In addition, the WshScriptExec object only
provides synchronous read operations on these streams. Synchronous
read operations introduce a dependency between the calling script
reading from these streams and the child process writing to those
streams, which can result in deadlock conditions.
I believe the problem is the way you read the stdout from the process. I use this technique succesfully as follows, sorry, I have no time to adapt your script and try it out, so that is up to you.
The following executes a ping to check if the server is online.
Function IsOnline(Address)
Dim strText
IsOnline = False
Set oExecObj = oShell.Exec("%comspec% /c ping -a -n 1 -w 20 " & Address)
Do While Not oExecObj.StdOut.AtEndOfStream
strText = oExecObj.StdOut.ReadAll()
If Instr(strText, "Reply from") > 0 Then
IsOnline = True
Exit Function
End If
Loop
End Function

Download multiple files from an FTP using VBScript

I'm not at all an expert at VB Scripting, but since it's a requirement at one of my projects for the moment, I am trying to write a VBScript that will GET all files from a specified FTP Folder.
I manage to get a single specified file, but I can't seem to get all files in a folder. Here's the script I'm trying to use:
Dim objOutStream
Const OpenAsDefault = -2
Const FailIfNotExist = 0
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutStream = objFSO.OpenTextFile("C:\temp\temp\empty.txt", ForWriting, True, TristateFalse)
With objOutStream
.WriteLine "USER myuser" ' USERNAME
.WriteLine "mypass" ' Password
.WriteLine "binary"
.WriteLine "prompt n"
.WriteLine "lcd /foldertocopyfrom" ' FOLDER I'm changing into
.WriteLine "mget *" ' Get all files with today's date in it
.WriteLine "bye"
.Close
End With
Set oFTPScriptShell = CreateObject("WScript.Shell")
oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & "C:\temp\temp\empty.txt" & " " & "ftp.location.com", 0, True
It doesn't give me an error or anything, it basically does nothing (and yes, I'm sure there are files in the /foldertocopy from :-))
Any ideas? Something obvious I am missing?
Thanks!
I tried your solution but had to make a couple small fixes to make it work:
Added Option Explicit (for better detection of undefined variables)
Removed the TristateFalse parameter
Removed prompt since toggle since interactive mode is already off
Changed bye to quit
Added -i parameter to the FTP command
Plus I tested your FTP command on the command line before using it in your script
Here's the modified script
Option Explicit
Const ForWriting = 2
Dim objOutStream, objFSO, objShell
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutStream = objFSO.OpenTextFile("C:\temp\temp\empty.txt", ForWriting, True)
With objOutStream
.WriteLine "USER myuser" ' USERNAME
.WriteLine "mypass" ' Password
.WriteLine "binary"
.WriteLine "lcd /foldertocopyfrom" ' FOLDER I'm changing into
.WriteLine "mget *" ' Get all files with today's date in it
.WriteLine "quit"
.Close
End With
Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /c FTP -n -i -s:" & "C:\temp\temp\empty.txt" & " " & "ftp.location.com", 0, True
I wrote a function to do this for you. You can read and examine it's code here:
http://www.naterice.com/articles/51
Please find below code to download from ftp location.
Function FTPDownload(sSite, sUsername, sPassword, sRemotePath)
Const ForWriting = 2
Dim objOutStream, objjFSO, objShell
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutStream = objFSO.OpenTextFile("C:\temp\temp\empty.txt", ForWriting, True)
With objOutStream
.WriteLine sUsername ' USERNAME
.WriteLine sPassword ' Password
.WriteLine "binary"
.WriteLine "cd /"& sRemotePath' FOLDER I'm changing into
.WriteLine "mget *" ' Get all files with today's date in it
.WriteLine "quit"
.Close
End With
Set objShell = CreateObject("WScript.Shell")
objShell.Run "%Comspec% /c FTP -i -s:" & "C:\temp\temp\empty.txt" & " " & sSite
End Function
Note e.g.
sSite : 192.168.0.1

Why do we need generate a temporary file when remote uploading to FTP?

I am so confused with this, I am trying to upload data to FTP through VBS script and it works fine for a single file file but doesn't upload multiple files when I add the script inside a loop.
Also , why do we need to generate a temporary file when remote uploading to FTP,
I mean to say this,
this is the script I am using,
Dim fso, folder, files, strPath
Set fso = CreateObject("Scripting.FileSystemObject")
strPath = "E:/Test"
Set folder = fso.GetFolder(strPath)
Set files = folder.Files
Const hostname = "ftp.domain.com"
Const port = 21
Const username = "username"
Const password = "password"
Const remoteDir = "/"
Const useDefaultsExclusively = True
Const skipConfirmation = True
For each item In files
If InStr(1, item.Name, "txt") <> 0 Then
defaultFile = item.Name
localFile = fso.getFileName(defaultFile)
localDir = fso.getParentFolderName(defaultFile)
Set shell = CreateObject("WScript.Shell")
tempDir = shell.ExpandEnvironmentStrings("%TEMP%")
' temporary script file supplied to Windows FTP client
scriptFile = tempDir & "\" & fso.GetTempName
' temporary file to store standard output from Windows FTP client
outputFile = tempDir & "\" & fso.GetTempName
'input script
script = script & "lcd " & """" & localDir & """" & vbCRLF
script = script & "open " & hostname & " " & port & vbCRLF
script = script & "user " & username & vbCRLF
script = script & password & vbCRLF
script = script & "cd " & """" & remoteDir & """" & vbCRLF
script = script & "binary" & vbCRLF
script = script & "prompt n" & vbCRLF
script = script & "put " & """" & localFile & """" & vbCRLF
script = script & "quit" & vbCRLF
Set textFile = fso.CreateTextFile(scriptFile, True)
textFile.WriteLine(script)
' bWaitOnReturn set to TRUE - indicating script should wait for the program
' to finish executing before continuing to the next statement
shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, TRUE
Wscript.Sleep 10
' open standard output temp file read only, failing if not present
Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2)
results = textFile.ReadAll
textFile.Close
End If
Next
fso.DeleteFile(scriptFile)
fso.DeleteFile(outputFile)
Why do we creating a Temporary file with this code, :S
Set shell = CreateObject("WScript.Shell")
tempDir = shell.ExpandEnvironmentStrings("%TEMP%")
' temporary script file supplied to Windows FTP client
scriptFile = tempDir & "\" & fso.GetTempName
' temporary file to store standard output from Windows FTP client
outputFile = tempDir & "\" & fso.GetTempName
Set textFile = fso.CreateTextFile(scriptFile, True)
textFile.WriteLine(script)
' bWaitOnReturn set to TRUE - indicating script should wait for the program
' to finish executing before continuing to the next statement
shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, TRUE
Wscript.Sleep 10
' open standard output temp file read only, failing if not present
Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2)
results = textFile.ReadAll
textFile.Close
Although I am looping through the script , it must upload every txt file inside current directory but it uploads only the first one, why is it so ?
When I print the current file i.e
MsgBox defaultfile
it display the name of each txt file inside the current folder but uploads first file only.
There is no native method of live automation for FTP. This is actually a scripting workaround. Your script is creating a text file with FTP instructions. Then, it launches FTP from the command line using the -s switch. That -s switch allows you to provide a text file containing session commands for FTP.exe to execute before closing. So while your script isn't actually automating the FTP program directly, it simulates automation by running FTP in "unattended mode". You can get a better understanding by opening a command prompt and typing ftp /?.
[EDIT]
I apologize, I missed your second question. Your script is only uploading the first file because it loops around the CreateTextFile method. This method is failing after the first attempt because the file already exists. What you really ought to do is loop around adding your files to the temporary file and then execute FTP only once. Your web server will appreciate the break as well.
Dim fso, folder, files, strPath
Set fso = CreateObject("Scripting.FileSystemObject")
strPath = "E:/Test"
Set folder = fso.GetFolder(strPath)
Set files = folder.Files
Const hostname = "ftp.domain.com"
Const port = 21
Const username = "username"
Const password = "password"
Const remoteDir = "/"
Const useDefaultsExclusively = True
Const skipConfirmation = True
tempDir = shell.ExpandEnvironmentStrings("%TEMP%")
' temporary script file supplied to Windows FTP client
scriptFile = tempDir & "\" & fso.GetTempName
' temporary file to store standard output from Windows FTP client
outputFile = tempDir & "\" & fso.GetTempName
Set textFile = fso.CreateTextFile(scriptFile, True)
'input script
textFile.WriteLine("open " & hostname & " " & port)
textFile.WriteLine("user " & username)
textFile.WriteLine(password)
textFile.WriteLine("cd " & Chr(34) & remoteDir & Chr(34))
textFile.WriteLine("binary")
textFile.WriteLine("prompt n")
For Each item In files
If InStr(1, item.Name, "txt") <> 0 Then
textFile.WriteLine("put " & Chr(34) & item.Path & "\" & item.Name & Chr(34))
End If
Next
textFile.WriteLine("quit")
textFile.Close
Set shell = CreateObject("WScript.Shell")
' bWaitOnReturn set to TRUE - indicating script should wait for the program
' to finish executing before continuing to the next statement
shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, True
WScript.Sleep 10
' open standard output temp file read only, failing if not present
Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2)
results = textFile.ReadAll
textFile.Close
fso.DeleteFile(scriptFile)
fso.DeleteFile(outputFile)

VBscript and CMD writing into a text file

I am writing a script that executes and write everything to the file
here is example,
I stored the complete command in the variable 'Command' ,
Command = "ftp ftp.xyz.com 21 " & vbCRLF
and then executing it in command prompt,
shell.Run "%comspec% /c FTP " & Command & " > " & E:/abc.txt, 0, TRUE
but when this program execute it won't write anything to the text file because this is an incomplete command, this command on execution prompt user to input username and password of FTP,
how can i do this , that my programm automatically input username and password when prompt and then write everything to file ?
You need to run FTP using an unattended script. (Try ftp /? and look at the -s switch.)
It looks like this:
Const HOSTNAME = "ftp.myserver.com"
Const USERNAME = "Login"
Const PASSWORD = "password"
Set WshShell = CreateObject("WScript.Shell")
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile = objFso.CreateTextFile("session.txt")
With objFile
.WriteLine "USER username"
.WriteLine "password"
.WriteLine "cd /public_html/" ' continue adding commands like this
.Close
End With
strOutput = "C:\somefilepath\output.txt"
strCommand = "%systemroot%\System32\ftp.exe -s:session.txt > " & strOutput
strCommand = WshShell.ExpandEnvironmentStrings(strCommand)
WshShell.Run strCommand, 0, vbTrue
objFso.DeleteFile "session.txt", vbTrue
You can read more in my article Using FTP in WSH on ASP Free. I also answered a related question here.

Resources