VBscript and CMD writing into a text file - shell

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.

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 & "\"

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 to grab newest file on ftp site

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

Psexec not outputting to log file in VB script

I have a VB script which needs to run psexec to launch an app called md5 on a remote server. Md5 generates a hash key of a file and takes one parameter - the file path\name. I need to retrieve the has key that is generated to store in a variable. Below is the code I am using:
Set objShell = CreateObject("Wscript.Shell")
strcomputer = "remotecomputer"
tempDest = "C:\somedir"
filename = "somefile"
strCommand = "psexec -accepteula \\" & strcomputer & " -c md5.exe " & tempDest & "\" & filename & " > log.txt"
Set objExecObject = objShell.Exec("%comspec% /c " & strCommand)
Do While objExecObject.Status <> 1 'loop until previous process has finished
WScript.Sleep 100
Loop
The MD5 command is run however nothing is written to the log file. When I copy and paste strCommand (substituting all the variables for the actual data) into a cmd prompt and run it, it successfully writes the output of Md5 to the log file.
At the end of the day I just need the output of Md5, if anyone knows a better way than writing it to a log file please let me know. I have already tried using objExecObject.StdOut.Readall() to try and catch the output which resulted in random failures - sometimes it would catch the output, sometimes it wouldn't, without changing anything in the script.
Just a guess: Are you sure about what the current directory is when the script is running? Try giving an absolute path to the log file and see if it helps.
I found a solution for this. Instead of using the following code:
strCommand = "psexec -accepteula \\" & strcomputer & " -c md5.exe " & tempDest & "\" & filename & " > log.txt"
Set objExecObject = objShell.Exec("%comspec% /c " & strCommand)
Do While objExecObject.Status <> 1 'loop until previous process has finished
WScript.Sleep 100
Loop
I used this instead:
strCommand = "psexec -accepteula \\" & strcomputer & " -c md5.exe " & tempDest & "\" & filename & " > log.txt"
objShell.Run "%comspec% /c " & strCommand, 0, true
The script is now redirecting to log.txt properly.

Resources