VBS expected statement error - vbscript

I keep getting a Error Expected statement. Code 800A0400. Line 1, char 1. What am I doing wrong?
My code,
# $language = "VBScript"
# $interface = "1.0"
' Connect to an SSH server using the SSH2 protocol. Specify the
' username and password and hostname on the command line as well as
' some SSH2 protocol specific options.
Sub Main
Dim host
host = "ssh.google.com"
Dim user
user = "userinfo"
' Prompt for a password instead of embedding it in a script...
'
Dim passwd
passwd = crt.Dialog.Prompt("Enter password for " & host, "Login", "", True)
' Build a command-line string to pass to the Connect method.
'
cmd = "/SSH2 /L " & user & " /PASSWORD " & passwd & " /C 3DES /M MD5 " & host
crt.Session.Connect cmd
End Sub

The "comment to end of line" marker in VBScript is the single quote ', not #. So change
# $language = "VBScript"
# $interface = "1.0"
to
' $language = "VBScript"
' $interface = "1.0"
(Other possible problems: do you call Sub main? Where does crt come from?)

Related

Secure CRT send command to an host VBS

Hey i have tried to make a simple script that can log in and send commands to the host/server:
Sub Main
crt.Screen.Synchronous = True
crt.Session.Connect "ip adress"
crt.Screen.WaitForString "Username: "
crt.Screen.Send "username" & chr(13)
crt.Screen.WaitForString "Password: "
crt.Screen.Send "password" & chr(13)
crt.Screen.Send "?" & chr(13)
crt.Screen.Synchronous = False
End Sub
my problem is it wont send anything.
Its working now:
Sub Main
host = Array("host1", "host2")
For each item in host
Dim user
user = "Username"
Dim passwd
passwd = "password"
cmd = "/SSH2 /L " & user & " /PASSWORD " & passwd & " /C AES-192-CTR /M SHA2-256 " & item
crt.Session.Connect cmd
Dim tab, index, nTabCount
nTabCount = crt.GetTabCount()
for index = 1 to nTabCount
set tab = crt.GetTab(index)
tab.activate
tab.screen.send "command" & vbcr
crt.Sleep 5000
crt.Session.Disconnect()
next
Next
End Sub

vbscript code to read input from text file avoiding manual efforts

I am drilling down Internet to get Vbscript code, where input is read from text file one per line and pass it to the commands in script. I am just a beginner and need help with this.
Basically I am gathering script to get pending patches of servers in our environment. The script looks like below:
'#
'# ServerPendingUpdates.vbs
'#
'# Usage: cscript ServerPendingUpdates.vbs {servername} {servername} {servername} {servername}
'# If no {servername} specified then 'localhost' assumed
'#
'# To do: Error handling
'#
Option Explicit
Dim strServer : strServer = GetArgValue(0,"localhost")
'#
'# Loop through the input parameters for each server
'#
Dim i
For i = 0 To WScript.Arguments.Count - 1
CheckServerUpdateStatus GetArgValue(i,"localhost") 'strServer
Next
WScript.Quit(0)
Function CheckServerUpdateStatus( ByVal strServer )
WScript.Echo vbCRLF & "Connecting to " & strServer & " to check software update status..."
Dim blnRebootRequired : blnRebootRequired = False
Dim blnRebootPending : blnRebootPending = False
Dim objSession : Set objSession = CreateObject("Microsoft.Update.Session", strServer)
Dim objUpdateSearcher : Set objUpdateSearcher = objSession.CreateUpdateSearcher
Dim objSearchResult : Set objSearchResult = objUpdateSearcher.Search(" IsAssigned=1 and IsHidden=0 and Type='Software'")
'#
'#
'#
Dim i, objUpdate
Dim intPendingInstalls : intPendingInstalls = 0
For i = 0 To objSearchResult.Updates.Count-1
Set objUpdate = objSearchResult.Updates.Item(I)
If objUpdate.IsInstalled Then
If objUpdate.RebootRequired Then
blnRebootPending = True
End If
Else
intPendingInstalls = intPendingInstalls + 1
'If objUpdate.RebootRequired Then '### This property is FALSE before installation and only set to TRUE after installation to indicate that this patch forced a reboot.
If objUpdate.InstallationBehavior.RebootBehavior <> 0 Then
'# http://msdn.microsoft.com/en-us/library/aa386064%28v=VS.85%29.aspx
'# InstallationBehavior.RebootBehavior = 0 Never reboot
'# InstallationBehavior.RebootBehavior = 1 Must reboot
'# InstallationBehavior.RebootBehavior = 2 Can request reboot
blnRebootRequired = True
End If
End If
Next
WScript.Echo strServer & " has " & intPendingInstalls & " updates pending installation"
If blnRebootRequired Then
WScript.Echo strServer & " WILL need to be rebooted to complete the installation of these updates."
Else
WScript.Echo strServer & " WILL NOT require a reboot to install these updates."
End If
'#
'#
'#
If blnRebootPending Then
WScript.Echo strServer & " is waiting for a REBOOT to complete a previous installation."
End If
End Function
'#
'#
'#
Function GetArgValue( intArgItem, strDefault )
If WScript.Arguments.Count > intArgItem Then
GetArgValue = WScript.Arguments.Item(intArgItem)
Else
GetArgValue = strDefault
End If
End Function
Basically I am looking for a code to put in somewhere there, where the server names input that shall be manually given after command execution in CLI can be given in a text file; like a lot of servers in text file and each server is executed one per line, one at a time by the script.
Cheers!
This allow to read from arguments collection and from standard input when - is passed as argument
Dim server
For Each server in WScript.Arguments.UnNamed
If server="-" Then
Do While Not WScript.StdIn.AtEndOfStream
WScript.Echo "Redirected: " + WScript.StdIn.ReadLine
Loop
Else
WScript.Echo "Argument: " + server
End If
Next
This allow to still pass arguments in the command line, and, if any of the arguments is a dash, the stantdard input is read. This will allow you to do any of the following
Usual argument pass
cscript checkServers.vbs server1 server2
Arguments and piped input
type servers.txt | cscript checkServers.vbs server1 server2 -
Only redirected input
cscript checkServers.vbs - < servers.txt
Redirected input and arguments
< servers.txt cscript checkServers.vbs - serverx
Or any other needed combination of arguments and standard input
type servers.txt | cscript checkservers.vbs server1 server2 - aditionalServer
EDITED to answer to comments
Option Explicit
Dim strServer
If WScript.Arguments.UnNamed.Length < 1 Then
CheckServerUpdateStatus "localhost"
Else
For Each strServer in WScript.Arguments.UnNamed
If strServer="-" Then
Do While Not WScript.StdIn.AtEndOfStream
strServer = Trim(WScript.StdIn.ReadLine)
If Len(strServer) > 0 Then CheckServerUpdateStatus strServer
Loop
Else
CheckServerUpdateStatus strServer
End If
Next
End If
WScript.Quit(0)
Obviously, you need to maintain your CheckServerUpdateStatus function, this code only handles the parameter input.
If you are trying to get the pending windows update installs for a bunch of computers, you can use this in Powershell:
$computers = gc text_file_of_computers.txt
ForEach ($computer in $computers) {
("-" * 30)+"`n" # Horizontal line
Write-Host "Patches not yet installed for $($computer)" -f "Yellow"
Get-Hotfix -co $computer| Where {$_.InstalledOn -eq $null}
"`n"+("-" * 30) # Horizontal line
}
As you can see, we only show patches which have a $null value for InstalledOn, which means they have not been installed as yet.
powershell

VBScript Carriage Returns

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

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
'

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