Upload
rob-dunn
View
112
Download
2
Embed Size (px)
DESCRIPTION
A presentation discussing the benefits of VBScripting in today's even with the advent of PowerShell. This presentation also discusses building an HTA for your VBScripts and accessing WMI and AD information.
Citation preview
AdminScripting as a Second Language
Rob DunnOctober 20th, 2011
Who the heck is this guy?
…seen a VBScript (or other) before and have used one in your network…downloaded one from the Spiceworks Script Center…dabbled in VBScripting but don’t know where to go next…wanted to get a little more from your current scripting skills
Assumptions
Hopefully you’ve…
• Anatomy of a VBScript (5 major elements)• Error Handling• Copying, Reading from, Writing to a file• Reading command-line results• Getting WMI and Active Directory Information• Building a GUI for your scripts
Recipe for a great script
What we’ll cover…
“Do you ever find yourself typing the same set of commands over and over to get a certain task done? Do you ever find yourself clicking the same set of buttons in the same sequence in the same wizard just to complete some chore - and then have to repeat the same process for, say, multiple computers or multiple user accounts?”
The power of scripting• Create or change user/computer accounts• Reset passwords• Upload or download files via FTP• Temp file/folder cleanups• Execute SQL backups• Get information about user/computer objects• Watch print queues• Email a user• Install software• .etc
Scripting. Why?
A good admin scripter should…
…allow for error handling…know how to debug…comment/document code…declare variables (best practice)…make your scripts as scaleable and generic as possible…be able to “Frankenscript”
Remember, there are lots of ways of doing the same thing with code. Do what makes sense to you
TM
Admin Scripting Skills
The Anatomy of a VBScript
• VBScript requires no additional software to be installed on older servers and workstations.
• VBScript is a runtime scripting language loosely based off of VBA and VB
• You can build a GUI for your VBScripts using HTA (Javascripts too)
• VBScript runs with less overhead, but it is not as powerful or intuitive as PowerShell
Why VBScript?
• Variables – a “container” where you can store values temporarily• Constant – a variable used like an alias (non-changing value)• Objects – a subset of predefined code which can allow access to
system level functions. You can use a variable to reference an object by using ‘Set’– Properties – read/writable attributes of a particular object– Methods – actions that can be performed with an object
• Functions – reusable code that can return a value via the calling command
• Subroutines – reusable code that can be executed to perform a special task
Anatomy
VBScript Fundamental Elements
VBScripts run as a .vbs or .vbe file http://goo.gl/KJ5op
There are two .exe’s which can run as the scripting host:
• Wscript.exe: outputs messages to separate windows as messages occur.
• Cscript.exe: outputs messages to the command-line interface in succession.
Depending on how you are implementing your scripts, you may choose to run one instead of the other.
Example: cscript.exe demo.vbs
VBScript hosts
Object method and property
Dim objFSO, objFIleSet objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.GetFile(“c:\windows\windowsupdate.log”)wscript.echo objFile.DateLastModified
Demo
Any time you wish to work with files, environment variables, Active Directory, WMI, the Windows Shell, etc. you will need to “create” the corresponding object in your code.
Anatomy
Variable/Constant
Dim strDescriptionstrDescription = “testing 1, 2, 3."Const SpiceworldDescription = “awesome”strDescription = “I think Spiceworld is hella ” _ & SpiceworldDescription wscript.echo strDescriptionWscript.echo “That was “ & SpiceworldDescription
Demo
Variables are temporary containers that may be repopulated during script execution with different values. Constants are variables with a permanent values which cannot be reset programmatically.
Anatomy
Function
Dim strFileName
wscript.echo funGetLastModified(“c:\windows\windowsupdate.log”)
Function funGetLastModified(strFilename)Dim objFSO, objFIleSet objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.GetFile(strFilename)funGetLastModified = objFile.DateLastModified
End function
Demo
Here, we are passing a variable to a function (a file path)…
…which is returned back to wscript.echo here.
Functions are used for returning values back directly to the code which called them.
Anatomy
SubroutineDim strFileDateCall subGetLastModified(“c:\windows\windowsupdate.log”)wscript.echo strFileDate
Sub subGetLastModifed(strFilename)Dim objFSO, objFIleSet objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.GetFile(strFilename)strFileDate = objFile.DateLastModified
End Sub
Demo
Subroutines are well suited for self-contained processes that don’t need to return values back to the originating code. Use it to work with items, files, etc. that remain somewhat independent from the rest of the script, such as displaying error messages.
Anatomy
• Typos/fat-fingering• Invalid use of variable data• Syntax problems• Logic problems• Etc.
How do we get around these problems?
Problems can arise from:
Error Handling
• You should always expect your scripts to encounter errors
• Anything encountered which isn’t expected is considered an “error” to the scripting engine
• In these cases, you’ll want to force the script to resume past errors and continue onward.
Use:On Error Resume Next
Error handling
Why?
Mind control
Dim Scott, objPerson
Set objPerson = CreateObject(“Scripting.PersonObject")Set Scott = objPerson.MindControl(“Scott Brosnan")
Scott.walk “through door”Scott.sing “Star Spangled Banner.wav”Scott.echo “All done!”
Option Explicit Dim Scott, objPerson
Set objPerson = CreateObject(“Scripting.PersonObject")On error resume nextSet Scott = objPerson.MindControl(“Scott Brosnan")
Scott.walk “through front door”Scott.sing “Star Spangled Banner.wav”Scott.echo “All done!”
Error handling
Let’s take a look at a few real world examples…
Copying a File
Option Explicit dim objFSOset objFSO = CreateObject("Scripting.FileSystemObject")objFSO.CopyFile "c:\temp\test.txt", "c:\temp\temp1\"MsgBox "Script finished."
Copying a file
If “test.txt” doesn’t exist on the computer running this script, the scripting host will produce an error and terminate.
Now that your script can make it past its first error…
Let’s use this to our advantage by utilizing the ‘err’ object. It has a couple important properties:
Err.number = provides numerical error Err.description = sometimes provides more descriptive detail about error
On error resume next‘other code goes hereIf err.number <> 0 then
Msgbox err.number & “ – “ & err.description
End If
Copying a file
Reading From a Text File
Reading from a text file via vbscript goes a bit like this:
1. Use the filesystem object to open a text file2. Either read the entire contents of the file into a
variable, or move through each line to process that line individually
3. Call a function or subroutine to do something with the information in that variable
Read from a text file
Read from a text file
In order to read from a text file, we need to state that we are going to use a constant and the filesystem object.
Next, we are going to open the file using the filesystem object (known as objFSO) by using the ‘OpenTextFile’ method.
If we are going to process each line, we will need to tell the script how to handle it until the file reaches the end (using the AtEndOfStream method).
Now you can execute code against whatever was in that line of the text file – in our case, we are going to display it with the ‘echo’ method.
Option Explicit Const ForReading = 1Dim objFSO, sourcefile
Set objFSO = CreateObject("Scripting.FileSystemObject")On error resume nextSet sourcefile = objFSO.OpenTextFile("c:\temp\computers.txt",ForReading)
Do Until sourcefile.AtEndOfStream = Truewscript.echo sourcefile.readline
Loop
Set objFSO = nothing
Writing to a text file
In order to write to a text file, we need to specify we are going to use a constant and the filesystem object. Note the ‘ForWriting’ constant (instead of ‘ForReading’).
Again, we are going to open the file using the filesystem object (known as objFSO) and use the ‘OpenTextFile’ method.
The FileSystemobject grants us a ‘writeline’ method, enabling you to write text directly to a file.
Option Explicit Const ForWriting = 2Dim objFSO, logfile
Set objFSO = CreateObject("Scripting.FileSystemObject")On error resume nextSet Logfile = objFSO.OpenTextFile("c:\temp\logfile.log", ForWriting, True)
Logfile.writeline("This is an entry in my logfile")
Logfile.closeSet objFSO = nothing
Write to a text file
Read Command-Line Output
Read command-line output
To read the output of a command line, we need to invoke the ‘wscript.shell’ object. This object allows us to execute a program using the ‘exec’ method.
We are going to place the output of the execute method into ‘objExecResults.’
In order to see our output in a readable format, we’ll use the ‘ReadAll’ method to read the contents of objExecResults into a variable or directly to the screen.
Option Explicit Dim WshShell, objExecResults
Set WshShell = CreateObject("WScript.Shell")Set objExecResults = WshShell.Exec("ping.exe 127.0.0.1")
wscript.echo objExecResults.StdOut.ReadAll
Other wshshell properties and methods
Properties• CurrentDirectory• Environment• SpecialFolders
Methods• AppActivate• CreateShortcut• Exec• ExpandEnvironmentStrings• LogEvent• Popup• RegDelete• RegRead• RegWrite• Run• SendKeys
Get sample usage and more details here: http://goo.gl/Rc3Z8
Wscript properties/methods
Wshnetwork properties and methods
Properties• ComputerName• UserDomain• UserName
Methods• MapNetworkDrive• EnumNetworkDrives• RemoveNetworkDrive• AddPrinterConnection• AddWindowsPrinterConnection• EnumPrinterConnections• SetDefaultPrinter• RemovePrinterConnection
Get sample usage and more details here: http://goo.gl/C9BT5
Wscript properties/methods
Getting WMI Info from Windows
• WMI is Microsoft’s implementation of Web-based Enterprise Management (WBEM)
• Every modern Windows computer has a localized WMI repository
• Spiceworks gets a lot of its data from the WMI repository
• WMI class examples: Win32_logicaldisk, Win32_bios, Win32_ComputerSystem
• You can quickly query local or remote repositories with VBScript, Powershell or Batch (etc.) scripts
WMI Queries
Think of the computer as the database, and the WMI classes at tables. You will query the various WMI classes as if you were querying a SQL database
What the heck is WMI?
To figure out how to query WMI via VBScript (or other languages), you’ll need:• Microsoft Scriptomatic 2.0-or-• WMIGen by Rob van der Woude
WMI Queries
These are tools which can allow you to generate specific code to import into your own scripts.
Microsoft Scriptomatic 2.0
WMIGen 7.03
Getting WMI Info:WMI Scripting, some examples
Option Explicit Dim objWMIService, strComputer, colItemsstrComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")On error resume nextSet colItems = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem", "WQL")
For Each objItem In colItemsWScript.Echo "BootDevice: " & objItem.BootDeviceWScript.Echo "Caption: " & objItem.CaptionWScript.Echo "Service Pack: " & objItem.ServicePackMajorVersion
Next
Instead of creating an object, we are getting an object, since this is already active. In this case, we are getting an object from the \root\CIMV2 namespace…
Next we are going to place the results of a WQL query into the colItems (collection) object.
This particular script will return the local or remote computer’s boot device, OS name and service pack level.WMI Queries – OS Details
Option Explicit Dim objWMIService, strComputer, colItemsstrComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_DiskDrive", "WQL")
For Each objItem In colItemsWScript.Echo "Caption: " & objItem.CaptionWscript.echo "Size: " & objItem.Size
Next
Here, we are querying the Win32_DiskDrive class…
Since the results are placed into a collection (colItems), then we must loop through it, even if there might be only one item in the collection.
WMI Queries – Disk Drives
Option Explicit Dim strComputer, objWMIService, colItems, strIPAddress
strComputer = "."Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")on error resume next
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration", "WQL")
For Each objItem In colItems WScript.Echo "Description: " & objItem.Description strIPAddress = Join(objItem.IPAddress, ",") WScript.Echo "IPAddress: " & strIPAddressNext
Notice the ‘Join’ function. Some adapters have more than one IP address.
WMI Queries – IP Addresses
Getting Active Directory Info
• Active Directory is a database of fields and values, think of a user/computer object as a record
• When querying AD, you should utilize filters to make your query more efficient
• You need to specify the attributes you wish to report against (pwdLastset, samAccountName,DN)
• You should try to isolate your queries to the OU structure where your results are located
Active Directory Info
Stuff you should know about Querying AD
Tools you will need
• Get AD Object Attributes VBScript http://goo.gl/csLFD• ADExplorer (SysInternals) – find your attributes• ADUC MMC – build your filter
Active Directory Info
Object Attribute Script Variables
The strFilter variable allows you to build your Active Directory filter. You can use the Microsoft ADUC to build this query and paste into this variable.
The strAttributes variable should be populated with the fields you would like the script to report back. Things like user name, computer name, account creation date, etc. can be returned…
Active Directory Info
Active Directory Info
There are MANY ways to get Active Directory data from your network.
Do what works for you…
Using an HTA as a GUI
• HTA (HyperText Application) is essentially a web page with full system privileges - think of HTML + VBScript
• If you can write HTML, you can make an HTA
• Great for single-task functions (reset a password)
Making a GUI with an HTA
What exactly is an “HTA?”
A simple HTA looks like this:<html><head><title>HTA Helpomatic</title>
<HTA:APPLICATION ID="objHTAHelpomatic" APPLICATIONNAME="HTAHelpomatic" SCROLL="yes" SINGLEINSTANCE="yes" WINDOWSTATE="maximize"></head>
<SCRIPT Language="VBScript"></SCRIPT><body>Well, this is boring, huh?</body></html>
Making a GUI with an HTA
Making a GUI with an HTA
<input type=“text” name=“filetocheck” id=“txtfiletocheck”>
<button type=“button” name=“check” id=“btnCheck” onclick=“funGetLastModified(txtfiletocheck.value)”>
<input type=“text” name=“computername” id=“txtComputer”><button type=“button” name=“ping” id=“btnPing” onclick=“ping(txtComputername.value)”>
Tools Summary
Tool Link (Case-sensitive)
Microsoft Scriptomatic v2.0 http://goo.gl/eL98u
Microsoft HTA-Helpomatic http://goo.gl/cCvDM
Rob van der Woude’s WMIGen http://goo.gl/jBNkv
PSPad Editor http://www.pspad.com
Notepad++ Editor http://notepad-plus-plus.org/
SysInternals’ ADExplorer http://goo.gl/hzX48
Resource Link (Case-sensitive)
Microsoft VBScript reference http://goo.gl/uDiFd
WScript Host object reference http://goo.gl/uJHWn
Get AD Object Attributes Script http://goo.gl/csLFD
Microsoft Script Center http://goo.gl/9BcyD
All built-in VBScript Functions http://goo.gl/iXza8
Helpful links