VBScript Carriage Returns - vbscript

I write the following VB script in order to run commands from WIN XP on Linux machine and redirect the output command to out.txt file ( under C:\ )
My VB script I print the /etc/hosts file from Linux machine in to out.txt file
Script works fine but I have one problem:
/etc/hosts file was printed in out.txt file with one long line , in place of three lines
Example: (out.txt)
127.0.0.1 localhost 19.20.183.99 MY_IP 10.10.10.10 LOOP
In place to print the following host file in out.txt
127.0.0.1 localhost
19.20.183.99 MY_IP
10.10.10.10 LOOP
MY VB script
Const TARGET_HOST = "19.20.183.99"
const PATH = "cat /etc/hosts"
const LOGIN = "root"
const PASS = " dgdgd "
Const PLINKPATH="""C:\dir1\plink.exe"""
Set Sh = CreateObject("WScript.Shell")
CMD = " echo y | " & PLINKPATH & " -ssh -pw " & PASS & LOGIN & "#" & TARGET_HOST & " " & PATH
Sh.Run "cmd /k" & CMD & " > ""C:\out.txt""" , 1, True
Please advice what I need to fix in my VB script in order to print the correct hosts file ( line by line ) and not as one long line ?

Try to do a replace of lf (line feed) for lf and cr (carriage return). Linux only has LFs, where windows also requires the carriage return to show the extra line.
Alternatively, open the file in Notepad++ and you'll notice that the lines are printed line by line. (http://notepad-plus-plus.org/download/v6.4.5.html)
EDIT:
Try the following after you outputted the file to replace the line feeds (reference: link):
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\out.txt", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, chr(10), chr(13) & chr(10))
Set objFile = objFSO.OpenTextFile("C:\out.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

Related

VBScript script as a wrapper for a silent Batch file

I have a batch file that gets some parameters from the command line and returns some values into STDOUT.
I want the batch file to be "silent" (such that the console is not shown), and found out probably the only possibility of using vbs script.
I used this thread for implementing the argument forwarding to the batch file in VBS.
Then, I used the following command for calling the batch file I wrapped:
CreateObject("WScript.Shell").Run batchFilePath & " " & Trim(arglist), 0, False
It turns out that my batch file does run, but its STDOUT is discarded somewhere, and does not make its way back to whom called the VBS script. I.e. the batch file's STDOUT is not redirected into the VBS script's STDOUT.
How can I make the batch file's STDOUT being redirected to the VBS script STDOUT, such that if I start the VBS script from some shell, the batch file's output will be printed to the shell too?
Use Exec instead of Run, like this:
set objShell = CreateObject( "WScript.Shell" )
cmd = "echo Hello World!"
' Run the process
set objRes = objShell.Exec( "cmd /c """ & cmd & """" )
' Wait for the child process to finish
Do While objRes.Status = 0
WScript.Sleep 100
Loop
' Show whatever it printed to its standard output
Wscript.Echo "The output was:" & vbNewLine & objRes.StdOut.ReadAll()
Try this...
Intreturn = WshShell.Run("cmd /c " & path& " " & args & ">c:\batchoutput.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set objfile = fso.OpenTextFile("c:\batchoutput.txt", 1)
text = objfile.ReadAll
Objfile.Close
Or try this...
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objexc = WshShell.Exec("cmd /c " & command and args) 'replace command and args with proper variables
strOutputText = ""
While Not objexc.StdOut.AtEndOfStream
strOutputText = strOutputText & objexc.StdOut.ReadLine()
Loop
Msgbox strOutputText
You may need some debugging on this.

Passing Caret to command line using VBScript

Having a hard time figuring this one out. I have a vbscript that asks for username and password. Then the script runs PSExec.exe passing those to the command line like this.
strUser = Inputbox("Username:","Username")
strPassword = Inputbox("Password:","Password")
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /K psexec.exe \\workstation -u " & struser _
& " -p " & strPassword & " -d calc.exe", 1, false
This works fine if the password doesn't have a caret in it. BUT if it does have one, for example if the password is "Pass)(*&^%$##!" I get the following error from psexec.
'%$##!' is not recognized as an internal or external command,
operable program or batch file.
The caret is being read by the command line as a space so it thinks it's trying to run this command.
psexec.exe \\workstation64 -u User -p Pass)(*& %$##! -d Calc.exe
As you can see there is a space instead of a caret so psexec see's %$##! as the command.
I've seen an example for passing it when using a batch file but it doesn't work in this case. It said adding an extra ^ like this ^^ works in a bat file.
How can I pass a caret to the command line????
UPDATE......
I worked on this for about 45 minutes today at work and couldn't get it to work. First thing I tried was to add quotes to the password and it still didn't work. I just tested it here at the house and it worked fine....... OS at work is Windows XP and at home I run Windows 7. I will try again in the morning to make sure I didn't mistype something. Here is what I did to make it work at home on Windows 7.
strUser = Inputbox("Username:","Username")
strPassword = Inputbox("Password:","Password")
strPassword = chr(34) & strPassword & chr(34)
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /K psexec.exe \\workstation -u " & struser _
& " -p " & strPassword & " -d calc.exe", 1, false
The problem lays in using of ampersand, not caret: single ampersand is used as a command separator, so rest of the line after &-sign considered to be a next command by cmd interpreter.
In next example I have used SET command instead of PSExec, as I will not experiment with PSExec.
All goes well with SET command, even if escaped all characters:), but I'm not sure about percentage sign, which is said "must be doubled to use literally".
Dim strPssw: strPssw = "/Pass"")=(*&^%$##!"
Dim ii, strChar, strEscape
Dim strPassword: strPassword = ""
For ii = 1 To Len( strPssw) 'cannot use Replace() function
strChar = Mid( strPssw, ii, 1)
Select Case strChar
Case "&", """", "^", "%", "=", _
"#", "(", ")", "!", "*", "?", _
".", "\", "|", ">", "<", "/"
strEscape = "^"
Case Else
strEscape = "" 'all goes well even if strEscape = "^" here
End Select
strPassword = strPassword & strEscape & strChar
Next
Dim objShell: Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /C set varia=" & strPassword & "&set varia&pause&set varia=", 1, false
' # - At Symbol: be less verbose
' & - Single Ampersand: used as a command separator
' ^ - Caret: general escape character in batch
' " - Double Quote: surrounding a string in double quotes escapes all of the characters contained within it
' () - Parentheses: used to make "code blocks" of grouped commands
' % - Percentage Sign: are used to mark some variables, must be doubled to use literally
' ! - Exclamation Mark: to mark delayed expansion environment variables !variable!
' * - Asterisk: wildcard matches any number or any characters
' ? - Question Mark: matches any single character
' . - Single dot: represents the current directory
' \ - Backslash: represent the root directory of a drive dir ^\
' | - Single Pipe: redirects the std.output of one command into the std.input of another
' > - Single Greater Than: redirects output to either a file or file like device
' < - Less Than: redirect the contents of a file to the std.input of a command
''
' && - Double Ampersand: conditional command separator (if errorlevel 0)
' .. - Double dot: represents the parent directory of the current directory
' || - Double Pipe: conditional command separator (if errorlevel > 0)
' :: - Double Colon: alternative to "rem" for comments outside of code blocks
' >> - Double Greater than: output will be added to the very end of the file
' thanks to http://judago.webs.com/batchoperators.htm
'

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.

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