57
Admin Scripting as a Second Language Rob Dunn October 20 th , 2011

Scripting as a Second Language

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

Page 1: Scripting as a Second Language

AdminScripting as a Second Language

Rob DunnOctober 20th, 2011

Page 2: Scripting as a Second Language

Who the heck is this guy?

Page 3: Scripting as a Second Language

…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…

Page 4: Scripting as a Second Language

• 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…

Page 5: Scripting as a Second Language

“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?”

Page 6: Scripting as a Second Language

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?

Page 7: Scripting as a Second Language

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

Page 8: Scripting as a Second Language

The Anatomy of a VBScript

Page 9: Scripting as a Second Language

• 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?

Page 10: Scripting as a Second Language

• 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

Page 11: Scripting as a Second Language

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

Page 12: Scripting as a Second Language

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

Page 13: Scripting as a Second Language

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

Page 14: Scripting as a Second Language

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

Page 15: Scripting as a Second Language

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

Page 16: Scripting as a Second Language

• Typos/fat-fingering• Invalid use of variable data• Syntax problems• Logic problems• Etc.

How do we get around these problems?

Problems can arise from:

Page 17: Scripting as a Second Language

Error Handling

Page 18: Scripting as a Second Language

• 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?

Page 19: Scripting as a Second Language

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!”

Page 20: Scripting as a Second Language

Error handling

Let’s take a look at a few real world examples…

Page 21: Scripting as a Second Language

Copying a File

Page 22: Scripting as a Second Language

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.

Page 23: Scripting as a Second Language

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

Page 24: Scripting as a Second Language

Reading From a Text File

Page 25: Scripting as a Second Language

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

Page 26: Scripting as a Second Language

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

Page 27: Scripting as a Second Language

Writing to a text file

Page 28: Scripting as a Second Language

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

Page 29: Scripting as a Second Language

Read Command-Line Output

Page 30: Scripting as a Second Language

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

Page 31: Scripting as a Second Language

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

Page 32: Scripting as a Second Language

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

Page 33: Scripting as a Second Language

Getting WMI Info from Windows

Page 34: Scripting as a Second Language

• 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?

Page 35: Scripting as a Second Language

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.

Page 36: Scripting as a Second Language

Microsoft Scriptomatic 2.0

Page 37: Scripting as a Second Language
Page 38: Scripting as a Second Language

WMIGen 7.03

Page 39: Scripting as a Second Language

Getting WMI Info:WMI Scripting, some examples

Page 40: Scripting as a Second Language

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

Page 41: Scripting as a Second Language

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

Page 42: Scripting as a Second Language

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

Page 43: Scripting as a Second Language

Getting Active Directory Info

Page 44: Scripting as a Second Language

• 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

Page 45: Scripting as a Second Language

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

Page 46: Scripting as a Second Language

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…

Page 47: Scripting as a Second Language

Active Directory Info

Page 48: Scripting as a Second Language

Active Directory Info

Page 49: Scripting as a Second Language

There are MANY ways to get Active Directory data from your network.

Do what works for you…

Page 50: Scripting as a Second Language

Using an HTA as a GUI

Page 51: Scripting as a Second Language

• 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?”

Page 52: Scripting as a Second Language

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

Page 53: Scripting as a Second Language

Making a GUI with an HTA

Page 54: Scripting as a Second Language

<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)”>

Page 55: Scripting as a Second Language

Tools Summary

Page 56: Scripting as a Second Language

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

Page 57: Scripting as a Second Language