db2 scripting with windows scripting host

34
DB2 UDB Scripting with Windows Scripting Host Chris Fierros Ten Digit Consulting November 2003

Upload: thecoreman

Post on 21-Apr-2015

182 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Db2 Scripting With Windows Scripting Host

DB2 UDB Scripting with Windows Scripting Host Chris Fierros

Ten Digit Consulting November 2003

Page 2: Db2 Scripting With Windows Scripting Host

Table of contents

Trademarks...................................................................................................................................... 3 Introduction ..................................................................................................................................... 3 Windows Scripting Host ................................................................................................................. 3

Core Object Model...................................................................................................................... 4 Execution Environment............................................................................................................... 5 Scripting Engines ........................................................................................................................ 8 Interfacing with DB2 .................................................................................................................. 8

WshShell Run Method............................................................................................................ 9 WshShell Execute Method ................................................................................................... 11

Scripting Languages ...................................................................................................................... 12 Scripting with JScript................................................................................................................ 13

DB2 Scripting with JScript ................................................................................................... 14 Scripting with VBScript............................................................................................................ 20

DB2 Scripting with VBScript ............................................................................................... 21 Scripting scenarios ........................................................................................................................ 27

DB2 Audit Facility Monitor Script ........................................................................................... 28 Conclusion..................................................................................................................................... 33 About the author............................................................................................................................ 34

Important: Read the disclaimer before reading this article.

Page 3: Db2 Scripting With Windows Scripting Host

Trademarks IBM, DB2, and DB2 Universal Database are trademarks or registered trademarks of IBM Corporation in the United States, other countries, or both. Microsoft, Windows, Windows NT, Windows 2000, Windows XP, and Windows Server 2003 are registered trademarks of Microsoft Corporation in the United States, other countries, or both. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. UNIX is a registered trademark of The Open Group in the United States and other countries. Other company, product, and service names may be trademarks or service marks of others.

Introduction In the first article of this series on DB2® Universal Database™ (UDB) and Windows Scripting, An Introduction to DB2 UDB Scripting on Windows I demonstrated how the DB2 Command Line Tools and DB2 system commands can be used to perform database administrative tasks from a command line interface. I also demonstrated how you can combine DB2 commands, DB2 system commands, and operating system command into a Windows Shell script to automate many of these tasks. In this second article we will cover in detail the more popular languages available for scripting on Windows, including Jscript and VBScript, that can be used to develop and deploy DB2 UDB scripts within the Windows Scripting Host (WSH) environment. Windows Scripting Host In general scripting refers to a language that is interpreted. Scripts are created in a text file and are not compiled into assembler or byte code before execution. Windows provides several environments that can be used to host scripting languages. Of these the most commonly ones used to perform system administration tasks are the Windows Shell (Wshell) and Windows Scripting Host (WSH) environments. The Windows Scripting Host (WSH) environment provides a standard execution environment for hosting scripts written in one or more supported scripting languages much like Internet Explorer provides a hosting environment for HTML, Java Scripts, and Java Applets. In fact, the WSH provides native support for both JScript and VBScript, which are commonly associated with Internet scripting. In addition to JScript and VBScript, many other scripting engines can be plugged into the WSH including IBM’s Object REXX and ActiveState’s PerlScript. Although none of these scripting languages require the WSH environment to execute, the WSH provides a number of benefits to the hosted scripting languages. The first is XML support which provides both a very intuitive interface for defining require and optional script arguments and support for scripts developed in more than one scripting language. The second is access to ActiveX controls that expose

Page 4: Db2 Scripting With Windows Scripting Host

automation interfaces such as the Windows Active Directory Service Interfaces (ADSI) and the Windows Management Instrumentation (WMI) interfaces both of which are supported by DB2 Universal Database v8.1. Microsoft provides a Script Encoder v1.0, downloadable from the Windows Script Technologies website (http://msdn.microsoft.com/scripting), which is a command line tool that enables script developers to encode their final script prior to deployment. This prevents users from viewing or modifying script code, but does not provide nearly as robust security as that provided by the WSH support for digital signatures. These digital signatures allow the authenticity of a script to be automatically verified before execution. Once digitally signed, system administrators can prevent unauthorized modifications of scripts and enforce strict security policies that determine whether a script can run locally or remotely. The most current version of Windows Script Host is 5.6 and it is built into Windows XP and Windows Server 2003 so there’s no need to install it. If you are running older version of Windows such Windows NT that did not include WSH or need to upgrade from previous versions of WSH that shipped with Windows 2000, you can download Windows Script Host version 5.6 from the Microsoft Windows Script Technologies website (http://msdn.microsoft.com/scripting). You will also find the Microsoft Script 5.6 Documentation package and other scripting utilities on this website. To check which version of WSH you currently have installed type cscript.exe at a Windows command prompt. The Windows Scripting Host (WSH) consists of three main components:

• Core Object Model • Execution Environment • Scripting Engines

Core Object Model The Core Object Model provides an ActiveX control named WSH.OCX that provides access to Windows objects. This is the component of WSH that allows interaction with the operating system, without it WSH would have very little use as an administrative scripting language. The WSH Core Object Model currently consists of fourteen objects shown in the table below.

Table 1. WSH Core Object Model

Object Description Wscript This object can be used to set and retrieve command line

arguments, determine the name of the script file, determine the host file name (wscript.exe or cscript.exe), determine the host version information, create, connect to, and disconnect from COM objects, sink events, stop a script's execution programmatically, and output information to the default output device (for example, a dialog box or the command line)

WshArguments This object can be used to access the entire set of command-line arguments.

WshNamed This object can be used to access the set of named command-line arguments,

Page 5: Db2 Scripting With Windows Scripting Host

WshUnnamed This object can be used to access the set of unnamed command-line arguments.

WshNetwork This object can be used to map and unmap network shares, connect to and disconnect from network shares and network printers, and access information about the currently logged-on user.

WshController This object can be used to create a remote script process using the Controller method CreateScript()

WshRemote This object can be used to remotely administer computer systems on a computer network and programmatically manipulate other programs or scripts.

WshRemote Error This object can be used to access the error information available when a remote script (a WshRemote object) terminates as a result of a script error.

WshShell This object can be used to run a program locally, manipulate the contents of the registry, create a shortcut, access a system folder, and manipulate environment variables.

WshShortcut This object can be used to programmatically create a shortcut. WshSpecialfolders This object can be used to access any of the Windows Special

Folders. WshURLShortcut This object can be used to programmatically create a shortcut to

an Internet resource WshEnvironment This object can be used to access the environment variables. WshScriptExec This object can be used to determine the status and error

information about a script run with Exec() and access the StdIn, StdOut, and StdErr channels.

Although the WSH Core Object Model is relatively small it can be used to script most Windows administrative tasks and can be significantly enhanced when combined with the Windows Management Instrumentation (WMI) and Active Directory Service Interface (ADSI) facilities. A complete discussion of the WSH Core Object Model is beyond the scope of this article, for more information visit the Microsoft Scripting Technology website (http://msdn.microsoft.com/scripting).

Execution Environment The Windows Scripting Host (WSH) execution environment requires that windows script files have a .wsf file extension. The WSH provides two execution environments. The default execution environment is wscript.exe which provides a "Windows" graphical user interface (GUI) environment. The second is cscript.exe which provides a "Command" line interface environment. You can set the default execution environment to cscript.exe using the //H:cscript option and back to wscript.exe using the //H:wscript option. This allows you to execute a WSH script file (*.wsf) in the execution environment of your choice without having to precede the script file with either wscript.exe or cscript.exe. The syntax for the cscript.exe execution environment is show below. Usage: cscript scriptname.extension [option...] [arguments...]

Page 6: Db2 Scripting With Windows Scripting Host

The table below lists all of the available options that can be passed to either the wscript.exe or cscript.exe execution environments.

Table 2. CScript and WScript Command Options

Options Description //B Batch mode: Suppresses script errors and prompts from displaying //D Enable Active Debugging //E:engine Use engine for executing script //H:cscript Changes the default scripting host to CScript.exe //H:wscript Changes the default scripting host to WScript.exe //I Interactive mode (default, opposite of //B) //Job:xxxx Execute a job defined within the WSF //Logo Display logo (default) //Nologo Suppress logo //S Save current command line options for this user //T:nn Time out in seconds: Maximum time a script is permitted to run //X Execute script in debugger //U Use Unicode for redirected I/O from the console As mentioned at the beginning of this section, the Windows Scripting Host (WSH) environment provides support for a limited set of tags from the Extensible Markup Language (XML) 1.0 standard to format Windows Script Files (*.wsf) that contain one or more embedded scripting language. These tags are listed in Table 3 below. Table 3. WSH Supported XML Tags

Element Description <?job?> XML processing instruction that specifies attributes for error handling. <?XML?> Indicates that a file should be parsed as XML. <description> Defines descriptive text that appears when the user runs ShowUsage() or runs

the script with the /? command line switch. <example> Defines example text that appears when the user runs ShowUsage() or runs

the script with the /? command line switch. <job> Defines the beginning and the end of a job within a Windows Script File

(.wsf) <named> Defines a named argument within a run-time argument. <object> XML element that is used in Windows Script component files and that

defines objects that can be referenced by script. <package> Encloses multiple job definitions in a Windows Script Host control (.wsf)

file. <reference> XML element that includes a reference to an external type library. <resource> XML element that isolates textual or numeric data that should not be hard-

coded into a script. <runtime> Defines a set of run-time arguments for a script. <script> Defines the beginning and end of a script within the Windows Script File

(*.wsf). <unnamed> Defines an unnamed argument within a run-time argument. <usage> Defines usage text that overrides the default usage text when the user runs

ShowUsage() or runs the script with the /? command line switch.

Page 7: Db2 Scripting With Windows Scripting Host

The XML tags are designed to provide information about the script, including a description, syntax, and any required or optional parameters. The following listing is an example of using XML tags within a WSH script. Listing 1. Sample WSH Script (hworld.wsf)

<job> <runtime> <description>hworld.wsf: This is a sample WSH script. </description> <named name="s" helpstring="salutation." type="string" required="true" /> <named name="l" helpstring="language." type="string" required="false" /> <example> Example: hworld.wsf /s:hello </example> </runtime> <script> WScript.Arguments.ShowUsage(); WScript.Quit(1); </script> </job> The listing above shows how the WSH provides support for XML tags within the WSH file. In this example the <named> tag defines two named command line parameters. The first is the salutation (name=”s”) that is a string (type=”string”) and a required parameter (required=”true”). The second is the language (name=”l”) parameter which is also a string (type=”string”) but is optional (required=”false”). Example 1. Sample WSH Script Output

Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. hworld.wsf: This is a sample WSH script. Usage: hworld.wsf /s:value [/l:value] Options: s : salutation. l : language. Example: hworld.wsf /s:hello The above example illustrates what is displayed on the console when the script is executed using the command line (cscript.exe) execution environment. The WScript.Arguments.ShowUsage() method formats the scripts XML tags. It first displays the contents of the <description> tag followed by the default usage and the values of the <helpstring> tags of the named command line options. Note that the usage shows the salutation “/s:value” parameter as required and the language “[/l:value]” as optional as it is inside brackets “[]”. The value of the <example> tag is also displayed.

Page 8: Db2 Scripting With Windows Scripting Host

The <usage> tag can be used to override these defaults as we have seen in the example above. If the <usage> tag exists, everything inside the <runtime> tag is ignored and only the text within the <usage> element is displayed. Here we have seen how simple XML tags can be very useful when impeded in a Windows Script File (*.wsf).

Scripting Engines Scripting engines are host independent scripting interpreters that plug into the WSH. Microsoft provides the JScript and VBScript scripting engines with the Windows Scripting Host (WSH). The WSH also provides support for plugging in other scripting engines. The latest version of both IBM’s Object REXX and ActiveState’s PerlScript are designed to plug into the WSH. We define the scripting engine to WSH using the <script> XML tag. In the listing below we show the <script language=”JScript”> XML tag to indicate the script language is Jscript. If we want to write our script in VBScript we use the <script language=”VBScript”> XML tag. If we want to plug in other scripting engines such as Object REXX or PerlScript we must identify the correct scripting engine defined by the scripting language supplier using the <script language=”value”> XML tag. Although not covered in this article, we could plug in Object REXX by using the <script language="Object REXX"> XML tag. Example 2. XML script language tag examples.

. . . <script language="JScript"> . . . </script> . . . <script language="VBScript"> . . . </script> . . . <script language="Object REXX"> . . . </script> . . . Using the <script language> XML tag, WSH provides the capability to mix scripts written in different scripting languages together, for example a single WSH script can be written in Jscript, VBScript, and any other supported scripting language. These scripts are placed in a file called a Windows Script File with a ".wsf" file extension. WSH uses XML to identify and manage this integration.

Interfacing with DB2 As we discovered in the first article in this series, An Introduction to Scripting DB2 UDB on Windows, DB2 commands and DB2 system commands are command line interfaces available with DB2 UDB that can be used within a Windows shell script. These command line interfaces can also be used to develop scripts within the Windows Scripting Host (WSH) environment. In this section I’ll show you how to instantiate (big word for create) a WshShell object and two methods that can be used to interface with DB2 UDB from any of the supported WSH languages.

Page 9: Db2 Scripting With Windows Scripting Host

At the beginning of this article we introduced the Core Object Model of the WSH. One of the objects in this model is the WshShell which can be used to run a program locally, manipulate the contents of the registry, create a shortcut, access a system folder, and manipulate environment variables. Once instantiated the WshShell object can be used to run or execute a DB2 Command Window (db2cmd.exe) that will be used to process DB2 commands as well as DB2 system commands. The following code example illustrates how to create a WshShell object using Jscript and VBScript. Example 3. Instantiate WshShell in Jscript and VBScript

. . . <script language="JScript"> var MyWshShell = new ActiveXObject("WScript.Shell"); </script> <script language="VBScript"> set MyWshShell = WScript.CreateObject("WScript.Shell") </script> . . . After the WshShell object has been instantiated there are two methods that can be used to create a DB2 Command Window (db2cmd.exe) process for invoking DB2 commands. The two WshShell methods that we will discuss in this section are:

• Run • Execute

WshShell Run Method The Run method can be used to create a DB2 Command Window (db2cmd.exe) as a child process and run a single DB2 command or multiple DB2 commands within a single DB2 script file. After the DB2 Command Window (db2cmd.exe) child process has completed running the DB2 command it terminates and a return code is passed back to the calling script. If additional DB2 commands need to be invoked, a new DB2 Command Window (db2cmd.exe) process must be created.

Listing 2. JScript using WshShell Run method to process DB2 command (db2cmdrun.js)

// // This is a sample JScript using WshShell run method to create a // DB2 Command Window (db2cmd.exe) child process. // var WshShell = new ActiveXObject("WScript.Shell"); WScript.StdOut.Write(WScript.ScriptName+".db2 backup database sample..."); var rc = WshShell.Run("db2cmd.exe -c -w -i db2 -l db2cmd.log backup database sample",0,true); if (rc != 0) { WScript.StdOut.WriteLine("failed, rc="+rc); } else { WScript.StdOut.WriteLine("complete, rc="+rc); }

Page 10: Db2 Scripting With Windows Scripting Host

// // Quit script passing back return code // WScript.Quit(rc); The advantage of using the Run method is that every invocation of the DB2 Command Window (db2cmd.exe) process via the Run method will provide a return code back to the calling script when the db2cmd.exe process terminates. A non-zero return code would mean that the command did not run successfully. In this example we use the DB2 CLP –l switch to log the results of the DB2 command to a file. If a non-zero return code is returned to the script you can optionally read and parse this file to get more detailed error information. The primary disadvantage of the run method is that a new DB2 Command Window db2cmd.exe process must be created for every DB2 Command you want to invoke. Furthermore, only one DB2 Command can be run per DB2 Command Window process. For example, an attach command followed by an update instance command would not be possible because the instance attachment would be lost when the first db2cmd.exe terminates. One technique to get around this limitation is to create a DB2 Script file that contains all the DB2 commands you want to invoke and then pass the DB2 script file to the DB2 Command Window (db2cmd.exe) process using the DB2 CLP "-tf" options.

Listing 3. JScript using WshShell Run method to process DB2 script (db2cmdruns.js)

// // This is a sample JScript using WshShell run method to create a // DB2 Command Window (db2cmd.exe) child process. // var WshShell = new ActiveXObject("WScript.Shell"); WScript.StdOut.Write(WScript.ScriptName+".db2 backup database sample..."); var rc = WshShell.Run("db2cmd.exe -c -w -i db2 -l db2cmd.log backup database sample",0,true); if (rc != 0) { WScript.StdOut.WriteLine("failed, rc="+rc); } else { WScript.StdOut.WriteLine("complete, rc="+rc); } // // Quit script passing back return code // WScript.Quit(rc); Listing 3 above shows the WshShell.Run code that can be used to implement this technique by simply modifying the WshShell. Run method code from the original script in Listing 2. The DB2 command switch "-s" indicates that processing of the DB2 script file should stop at the first command error that is encountered. The DB2 command switch "-t" indicates that each command within the DB2 Script file is terminated, by default DB2 uses a simi-colon";". The DB2 command switch "-f" indicates that the input for the DB2 CLP will be from a file, see Listing 4. This file can contain as DB2 system commands and operating system commands as well as long as these commands are preceded with a bang “!”.

Page 11: Db2 Scripting With Windows Scripting Host

Listing 4. DB2 Backup Script (db2ackupruns.db2)

-- -- This is a sample DB2 Backup Script -- ATTACH TO DB2; BACKUP DATABASE SAMPLE; DETACH; TERMINATE; Yet another technique that can be used to get around the limitation of the WshShell run method is to use the execute method which we will cover in the section that follows.

WshShell Execute Method As with the run method, the WshShell execute method can be used to start a DB2 Command Window (db2cmd.exe) as a child process to your WSH script to run DB2 commands. However, a DB2 Command Window (db2cmd.exe) created with the WshShell execute method does not immediately terminate after processing a DB2 command as does the WshShell run method. Once the WshShell execute method has been used to create a DB2 Command Windows (db2cmd.exe) child process, it is available to process as many DB2 commands, DB2 system commands, and operating system commands as needed. The advantage of using the Execute method is that only a single DB2 Command Window (db2cmd.exe) process is required and it can be used to process multiple DB2 commands. For example, an instance attachment command followed by a database backup command. Another benefit to using the Execute method is that it provides better control of standard input, output, and error streams. This is of little importance for scripts that run in batch mode at 2:00 am, but it an added feature for scripts intended to run in interactive mode as you have full control of what information is displayed on the console.

Listing 5. JScript using WshShell Execute method to process DB2 commands (db2cmdexc.js)

// // This is a sample JScript using WshShell execute method to create a // DB2 Command Window (db2cmd.exe) child process. // var MyWshShell = new ActiveXObject("WScript.Shell"); var MyDb2Cmd = MyWshShell.Exec("db2cmd.exe -i "); // // Write db2 backup database command to MyDb2Cmd // WScript.StdOut.Write(WScript.ScriptName+".db2 backup database sample..."); MyDb2Cmd.StdIn.WriteLine("db2 +o -ec backup database sample"); if (jsDb2SqlCodeCheck()) { WScript.StdOut.WriteLine("done!"); } // // Write exit to MyDb2Cmd // MyDb2Cmd.Stdin.WriteLine("exit"); while (MyDb2Cmd.Status == 0) { WScript.Sleep(250); }

Page 12: Db2 Scripting With Windows Scripting Host

// // Quit script passing back return code // WScript.Quit(MyDb2Cmd.ExitCode); //****************************************************************************// This function checks for errors in the db2cmd stdout. //****************************************************************************function jsDb2SqlCodeCheck() { var linein = MyDb2Cmd.StdOut.ReadLine(); while (!MyDb2Cmd.StdOut.AtEndOfStream) { var linein = MyDb2Cmd.StdOut.ReadLine(); if (linein.length > 0) { if (linein != 0) { WScript.StdOut.WriteLine( "failed, sqlcode=" + linein ); return 0; } else break; } WScript.Sleep(250); } return 1 } The primary disadvantage of using the Execute method is that return code processing is some what more complex because the DB2 Command Window (db2cmd.exe) process does not provide the script with a return code until the process terminates. This limitation requires that you write a return code routine to properly identify the results of the DB2 command that was executed by the DB2 Command Window (db2cmd.exe) process. There are a number of techniques that can be use to implement this return code processing logic. The most common technique that you are probably already familiar with requires that you use the –l DB2 command option to generate a log file for all DB2 commands. You can then open the log file, parse the information in the log, and retrieve the return code for the DB2 command. Another technique you can use, shown in Listing 5 above, is to invoke the StdOut.ReadLine method against the WshShell object to retrieve and parse the standard output generated by the DB2 Command Window using the +o –ec DB2 command option. The +o DB2 command option suppresses all output from the DB2 Command. The –ec DB2 command option tells the command line processor to display the SQLCODE from the DB2 command. Once you have retrieved a non-zero SQLCODE you can then optionally read and parse the log file generated by the DB2 Command Window using the –l DB2 command option to get more information about the error code. I’ll show you how to implement these techniques in sample scripts included in the rest of this article. Scripting Languages In the previous section we introduced the Windows Scripting Host (WSH) environment. In this section we will introduce scripting languages that plug into WSH and I’ll show you how to write DB2 UDB scripts with these languages within the WSH environment. All of the languages

Page 13: Db2 Scripting With Windows Scripting Host

discussed in this article can be used with or without the Windows Scripting Host (WSH). Deciding on which scripting language to use is more a matter of preference or programming style as they all provide the same functionality. Although we won’t cover IBM’s Object REXX in this article it is worth mentioning that DB2 UDB provides a native Application Programming Interface (API) for REXX which clearly provides this language some advantages. At this point in the article you may decide to skip to the section in the article related to the scripting language you are most interested in learning how to script with DB2 Universal Database as the code samples provided are identical in function but written in either Jscript or VBScript.

Scripting with JScript JScript is Microsoft’s implementation of the ECMA 262 language specification similar to Netscape’s JavaScript language. Although it does contain some features that are not compliant with the ECMA standards such as Java like error handling with the throw, try, catch, and finally statements. JScript is an object-based interpreted scripting language that is one of the two key scripting languages included with the Windows Scripting Host v5.6. You may choose to begin scripting with JScript if you have a Java programming background or you have done web page development with JavaScript. Scripts written in JScript that are embedded within a Windows script file (a file name with a WSF file extension) must be wrapped within a begin script <script language=”Jscript”> and end script </script> tags so that the WSH can identify and submit the script to the appropriate scripting engine. JScript scripts that are written outside of a Windows script file (WSF) still run under the control of the Windows Scripting Host and must be placed in a file with a file extension of ".js" for example “myscript.js”. Although the WSH includes an object model that provides access to Windows objects, JScript also has its own object model that provides access to the objects as well. A complete discussion of the Jscript Object Model is beyond the scope of this article, for more information you will find the Jscript Documentation link on the Microsoft Scripting Technology website (http://msdn.microsoft.com/scripting). The JScript object model includes:

• ActiveXObject • Array • Boolean • Date • Dictionary • Enumerator • Error • FileSystemObject • Function • Global • Math • Number • Object • RegExp

Page 14: Db2 Scripting With Windows Scripting Host

• Regular Expression • String • VBArray

In addition to these objects, JScript provides a collection of runtime system objects that include:

• Dictionary • Drive and Drives • File and Files • FileSystemObject • Folder and Folders • TextStream

The following listing is our “Hello World” script written in JSscript. Listing 4. Sample JScript (hworld.js)

// This is a sample JScript script. WScript.Echo("Hello World!"); The following listing is the same JScript impeded within a Windows Script File (.wsf). Note the script XML tag <script language=”Jscript”> which defines the scripting engine to WSH.

Listing 5. Sample JScript within WSF (hworldjs.wsf)

<job> <runtime> <description>hworld.wsf: This is a sample WSH script. </description> <named name="s" helpstring="salutation." type="string" required="true" /> <named name="l" helpstring="language." type="string" required="false" /> <example> Example: hworld.wsf /s:hello </example> </runtime> <script language="JScript"> if (!WScript.Arguments.Named.Exists("s")) { WScript.Arguments.ShowUsage(); WScript.Quit(0); } else { WScript.Echo('Hello World from JScript!'); } WScript.Quit(1); </script> </job>

DB2 Scripting with JScript In this section I’ll show you a complete example of how to use Jscript within Windows Scripting Host (WSH) to perform a backup of the sample database. The code in this example is divided into two files. The first file (db2backupjs.wsf) contains the main Jscript code to perform the

Page 15: Db2 Scripting With Windows Scripting Host

database backup. You can use this main script file as a template to automate other DB2 Administrative tasks. The second file (jsdb2lib.js) consists of a library of common DB2 functions, also written in Jscript that can be referenced by any other of scripts you develop. As you continue to write more scripts, simply add your new functions to this library. Listing 8 below shows the main code in this example. Using the XML tag support we can see that it provides for several required and optional command line parameters. As with our previous examples, if the required parameters are not provided the script displays the appropriate usage information. Unlike our previous examples, this script includes a reference to another script file using the <script language="JScript" src="jsdb2lib.js"/> tag. This second script file, also written in Jscript, provides all of the functions called by the main script file (db2backupjs.wsf). Using this technique allows us to develop a common DB2 function library that can be re-used in any other script we develop that can be written in any language supported by the WSH. Listing 8. DB2 Backup Script in WSH using Jscript (db2backupjs.wsf) <job> <runtime> <description>db2backupjs.wsf: JScript Script to backup database. </description> <named name="i" helpstring="instance." type="string" required="false"/> <named name="d" helpstring="database." type="string" required="true"/> <named name="t" helpstring="target." type="string" required="false"/> <named name="u" helpstring="userid." type="string" required="false"/> <named name="p" helpstring="password." type="string" required="false"/> <example> Example: db2backupjs.wsf /d:SAMPLE </example> </runtime> // // Include JScript DB2 Function Library // <script language="JScript" src="jsdb2lib.js"/> // // Main Script // <script language="JScript"> // // Determine if required parameters exist, if not show usage // if (!WScript.Arguments.Named.Exists("d")) { WScript.Arguments.ShowUsage(); WScript.Quit(0); } else { // // Initialize global variables

Page 16: Db2 Scripting With Windows Scripting Host

// var program = WScript.ScriptName var version = "1.0" WScript.StdOut.WriteLine("*******************************************************************************"); WScript.StdOut.WriteLine(program + " Version " + version); WScript.StdOut.WriteLine("*******************************************************************************"); // // Assign arguments to variables // var instance = WScript.Arguments.Named("i"); var database = WScript.Arguments.Named("d"); var target = WScript.Arguments.Named("t"); var userid = WScript.Arguments.Named("u"); var password = WScript.Arguments.Named("p"); // // Create db2cmd process // var WshShell = new ActiveXObject("WScript.Shell"); var db2cmd = WshShell.Exec("db2cmd.exe -i "); // // If instance was provided attach to it // if (instance) { var rc = jsDb2Attach(instance,userid,password); } // // Backup database // var rc = jsDb2BackupDatabase(database,target); // // If instance was provided detach from it // if (instance) { var rc = jsDb2Detach(); } // // Terminate and Exit db2cmd process // db2cmd.Stdin.WriteLine("db2 terminate") db2cmd.Stdin.WriteLine("exit") while (db2cmd.Status == 0) { WScript.Sleep(250); } } // // Quit script passing back return code // WScript.Quit(1); </script> </job>

Page 17: Db2 Scripting With Windows Scripting Host

Listing 9 below shows the Jscript DB2 Library script file that is referenced by our main script using the <script language="JScript" src="jsdb2lib.js"/> tag. All lines in this script file before the first function declaration are executed when the primary script file interprets the <script language="JScript" src="jsdb2lib.js"/> tag. In the code below we establish a file system object for reading the DB2 command windows log file that will be generated using the –l DB2 command option. The first function, jsDb2Attach, is used to attach to a DB2 instance. The second function, jsDb2Detach, is used to detach from a DB2 instance. The third function, jsDb2BackupDatabase, performs the database backup. All of these functions create a DB2 command string and write it to the WshShell object db2cmd using the db2cmd.Stdin.WriteLine method and then call the jsDb2SqlCodeCheck function. Several DB2 command options are included in the DB2 command we write to the WshShell object called db2cmd. The +o DB2 command option suppresses all normal output that would otherwise be displayed on the console. The –ec DB2 command option forces the DB2 command line processor to display the SQLCODE from the executed command. The –l DB2 command option logs the execution of the DB2 command to the specified log file db2cmd.log. If a non-zero SQLCODE is returned from the DB2 command windows we can optionally open, read, and parse this file for a more detailed error message. Listing 9. DB2 Script Library in WSH using Jscript (jsdb2lib.js) //****************************************************************************// jsdb2lib: JScript DB2 lib Library contains DB2 functions in JScript. // Insert <script language="JScript" src="jsdb2lib.js"/> in your script // to reference these functions. //****************************************************************************// // Create db2cmd log file // var ForReading = 1, ForWriting = 2, ForAppending = 8; var fso = new ActiveXObject("Scripting.FileSystemObject"); if (fso.FileExists("db2cmd.log")) fso.DeleteFile("db2cmd.log"); //****************************************************************************// This function attaches to a db2 instance. //****************************************************************************function jsDb2Attach(instance,userid,password) { WScript.StdOut.Write(program+".jsDb2Attach("+instance+")..."); if (fso.FileExists("db2cmd.log")) fso.DeleteFile("db2cmd.log"); if (password != undefined) var db2command = ("db2 +o -ec -l db2cmd.log attach to "+instance+" user "+userid+" using "+password); else if (userid != undefined) var db2command = ("db2 +o -ec -l db2cmd.log attach to "+instance+" user "+userid); else var db2command = ("db2 +o -ec -l db2cmd.log attach to "+instance);

Page 18: Db2 Scripting With Windows Scripting Host

db2cmd.Stdin.WriteLine( db2command ); if (jsDb2SqlCodeCheck()) return 1; else return 0; } //****************************************************************************// This function detaches from a db2 instance. //****************************************************************************function jsDb2Detach() { WScript.StdOut.Write(program+".jsDb2Detach()..."); if (fso.FileExists("db2cmd.log")) fso.DeleteFile("db2cmd.log"); var db2command =("db2 +o -ec -l db2cmd.log detach "); db2cmd.Stdin.WriteLine( db2command ); if (jsDb2SqlCodeCheck()) return 1; else return 0; } //****************************************************************************// This function connect to the db2 database //****************************************************************************function jsDb2Connect(instance,userid,password) { WScript.StdOut.Write(program+".jsDb2Connect("+instance+")..."); if (fso.FileExists("db2cmd.log")) fso.DeleteFile("db2cmd.log"); if (password != undefined) var db2command = ("db2 +o -ec -l db2cmd.log connect to "+database+" user "+userid+" using "+password); else if (userid != undefined) var db2command = ("db2 +o -ec -l db2cmd.log connect to "+database+" user "+userid); else var db2command = ("db2 +o -ec -l db2cmd.log connect to "+database); db2cmd.Stdin.WriteLine( db2command ); if (jsDb2SqlCodeCheck()) return 1; else return 0;

Page 19: Db2 Scripting With Windows Scripting Host

} //****************************************************************************// This function disconnect from the db2 database //****************************************************************************function jsDb2ConnectReset() { WScript.StdOut.Write(program+".jsDb2ConnectReset()..."); if (fso.FileExists("db2cmd.log")) fso.DeleteFile("db2cmd.log"); var db2command =("db2 +o -ec -l db2cmd.log connect reset"); db2cmd.Stdin.WriteLine( db2command ); if (jsDb2SqlCodeCheck()) return 1; else return 0; } //****************************************************************************// This function performs the database backup. //****************************************************************************function jsDb2BackupDatabase(database,target) { WScript.StdOut.Write(program+".jsDb2BackupDatabase("+database+")..."); if (fso.FileExists("db2cmd.log")) fso.DeleteFile("db2cmd.log"); if (target != undefined) var db2command =("db2 +o -ec -l db2cmd.log backup database "+database+' to '+target); else var db2command =("db2 +o -ec -l db2cmd.log backup database "+database ); db2cmd.Stdin.WriteLine( db2command ); if (jsDb2SqlCodeCheck()) return 1; else return 0; } //****************************************************************************// This function checks for errors in the db2cmd stdout. //****************************************************************************function jsDb2SqlCodeCheck() { var linein = db2cmd.StdOut.ReadLine(); while (!db2cmd.StdOut.AtEndOfStream) { var linein = db2cmd.StdOut.ReadLine(); if (linein.length > 0)

Page 20: Db2 Scripting With Windows Scripting Host

{ if (linein == 0) { WScript.StdOut.WriteLine( "complete, sqlcode=" + linein ); break; } else if (linein > 0) { WScript.StdOut.WriteLine( "oops, sqlcode=" + linein ); break; } else { WScript.StdOut.WriteLine( "failed, sqlcode=" + linein ); return 0; } } else break; WScript.Sleep(250); } return 1 } The last function, jsDb2SqlCodeCheck, reads the DB2 Command Window’s standard output to retrieve the SQLCODE returned from the DB2 command that was executed. In this function you could optionally open, read, and parse the log file db2cmd.log created by the DB2 Command Window if a non-zero SQLCODE was encountered.

Scripting with VBScript VBScript is a scripting language with roots from Microsoft's own implementation of the Visual Basic programming language. It is the second of two key scripting languages included with the Windows Scripting Host v5.6. You may decide to choose VBScript if you have a Visual Basic or Visual Basic for Applications (VBA) programming background or you have done web page development with VBScript. Scripts written in VBScript that are embedded within a Windows script file (a file name with a WSF file extension) must be wrapped within a begin script <script language=”VBScript”> and end script </script> tags so that the WSH can identify and submit the script to the appropriate scripting engine. VBScript scripts that are written outside of a Windows script file (WSF) still run under the control of the WSH and must be placed in a file with a file extension of ".vbs", for example “myscript.vbs”. Although the WSH includes an object model that provides access to Windows objects, VBScript also has its own object model that provides access to the objects as well. A complete discussion of the VBScript Object Model is beyond the scope of this article, for more information you will find the VBScript Documentation link on the Microsoft Scripting Technology website (http://msdn.microsoft.com/scripting). The VBScript object model includes:

• Class • Dictionary

Page 21: Db2 Scripting With Windows Scripting Host

• Err • FileSystemObject • Match, Matches, and Submatches • RegExp

In addition to these objects, VBScript provides a collection of runtime system objects that include:

• Dictionary • Drive and Drives Collection • File and Files Collection • FileSystemObject • Folder and Folders Collection

The following listing is our “Hello World” script written in VBScript. Listing 10. Sample VBScript (hworld.vbs)

' This is a sample VBScript script. Wscript.echo "Hello World!" The following is the same VBScript listing impeded within a Windows Script File (.wsf). Note the script XML tag <script language=”VBScript”> which defines the scripting engine to WSH. Listing 11. Sample VBScript within WSF (hworldvbs.wsf)

<job> <runtime> <description>hworld.wsf: This is a sample WSH script. </description> <named name="s" helpstring="salutation." type="string" required="true" /> <named name="l" helpstring="language." type="string" required="false" /> <example> Example: hworld.wsf /s:hello </example> </runtime> <script language="VBScript"> if not WScript.Arguments.Named.Exists("s") then WScript.Arguments.ShowUsage() WScript.Quit(0) else WScript.Echo "Hello World from VBScript!" end if WScript.Quit(1) </script> </job>

DB2 Scripting with VBScript In this section I’ll show you a complete example of how to use VBScript within Windows Scripting Host (WSH) to perform a backup of the sample database. The code in this example is

Page 22: Db2 Scripting With Windows Scripting Host

divided into two files. The first file (db2backupvb.wsf) contains the main VBScript code to perform the database backup. You can use this main script file as a template to automate other DB2 Administrative tasks. The second file (vbdb2lib.vbs) consists of a library of common DB2 functions, also written in VBScript that can be referenced by any other of scripts you develop. As you continue to write more scripts, simply add your new functions to this library. Listing 12 below shows the main code in this example. Using the XML tag support we can see that it provides for several required and optional command line parameters. As with our previous examples, if the required parameters are not provided the script displays the appropriate usage information. Unlike our previous examples, this script includes a reference to another script file using the <script language="VBScript" src="vbdb2lib.vbs"/> tag. This second script file, also written in VBScript, provides all of the functions called by the main script file (db2backupvb.wsf). Using this technique allows us to develop a common DB2 function library that can be re-used in any other script we develop that can be written in any language supported by the WSH. Listing 12. DB2 Backup Script in WSH using VBScript (db2backupvb.wsf) <job> <runtime> <description>db2backupvb.wsf: VBScript Script to backup database. </description> <named name="i" helpstring="instance." type="string" required="false"/> <named name="d" helpstring="database." type="string" required="true"/> <named name="t" helpstring="target." type="string" required="false"/> <named name="u" helpstring="userid." type="string" required="false"/> <named name="p" helpstring="password." type="string" required="false"/> <example> Example: db2backupvb.wsf /d:SAMPLE </example> </runtime> ' ' Include VBScript DB2 Function Library ' <script language="VBSCript" src="vbdb2lib.vbs"/> ' ' Main Script ' <script language="VBScript"> ' ' Determine if required parameters exist, if not show usage ' if not WScript.Arguments.Named.Exists("d") then WScript.Arguments.ShowUsage() WScript.Quit(0) else ' ' Initialize global variables ' program = WScript.ScriptName

Page 23: Db2 Scripting With Windows Scripting Host

version = "1.0" WScript.StdOut.WriteLine("*******************************************************************************") WScript.StdOut.WriteLine(program & " Version " & version) WScript.StdOut.WriteLine("*******************************************************************************") ' ' Assign arguments to variables ' instance = WScript.Arguments.Named("i") database = WScript.Arguments.Named("d") target = WScript.Arguments.Named("t") userid = WScript.Arguments.Named("u") password = WScript.Arguments.Named("p") ' ' Create db2cmd process ' set WshShell = CreateObject("WScript.Shell") set db2cmd = WshShell.Exec("db2cmd.exe -i ") ' ' If instance was provided attach to it ' if not IsEmpty(instance) then rc = vbDb2Attach(instance,userid,password) end if ' ' Backup database ' rc = vbDb2BackupDatabase(database,target) ' ' If instance was provided detach from it ' if not IsEmpty(instance) then rc = vbDb2Detach() end if ' ' Terminate and Exit db2cmd process ' db2cmd.Stdin.WriteLine("db2 terminate") db2cmd.Stdin.WriteLine("exit") do while db2cmd.Status = 0 WScript.Sleep(250) loop end if ' ' Quit script passing back return code ' WScript.Quit(1) </script> </job> Listing 13 below shows the VBScript DB2 Library script file that is referenced by our main script using the <script language="VBScript" src="vbdb2lib.vbs"/> tag. All lines in

Page 24: Db2 Scripting With Windows Scripting Host

this script file before the first function declaration are executed when the primary script file interprets the <script language="VBScript" src="vbdb2lib.vbs"/> tag. In the code below we establish a file system object for reading the DB2 command windows log file that will be generated using the –l DB2 command option. The first function, vbDb2Attach, is used to attach to a DB2 instance. The second function, vbDb2Detach, is used to detach from a DB2 instance. The third function, vbDb2BackupDatabase, performs the database backup. All of these functions create a DB2 command string and write it to the WshShell object db2cmd using the db2cmd.Stdin.WriteLine method and then call the vbDb2SqlCodeCheck function. Several DB2 command options are included in the DB2 command we write to the WshShell object called db2cmd. The +o DB2 command option suppresses all normal output that would otherwise be displayed on the console. The –ec DB2 command option forces the DB2 command line processor to display the SQLCODE from the executed command. The –l DB2 command option logs the execution of the DB2 command to the specified log file db2cmd.log. If a non-zero SQLCODE is returned from the DB2 command windows we can optionally open, read, and parse this file for a more detailed error message. Listing 13. DB2 Script Library in WSH using VBScript (vbdb2lib.vbs) '***************************************************************************** ' vbdb2lib: VBScript DB2 lib Library contains DB2 functions in VBScript. ' Insert <script language="VBSCript" src="vbdb2lib.vbs"/> in your script ' to reference these functions. '***************************************************************************** ' ' Create db2cmd log file for error ' Const ForReading = 1, ForWriting = 2, ForAppending = 8 set fso = CreateObject("Scripting.FileSystemObject") if fso.FileExists("db2cmd.log") then fso.DeleteFile("db2cmd.log") end if '***************************************************************************** ' This function attaches to the db2 instance '***************************************************************************** function vbDb2Attach(instance,userid,password) WScript.StdOut.Write(program & ".vbDb2Attach(" & instance & ")...") if fso.FileExists("db2cmd.log") then fso.DeleteFile("db2cmd.log") end if if not IsEmpty(password) then db2command = "db2 +o -ec -l db2cmd.log attach to " & instance & " user " & userid & " using " & password elseif not IsEmpty(userid) then db2command = "db2 +o -ec -l db2cmd.log attach to " & instance & " user " & userid

Page 25: Db2 Scripting With Windows Scripting Host

else db2command = "db2 +o -ec -l db2cmd.log attach to " & instance end if db2cmd.Stdin.WriteLine( db2command ) if vbDb2SqlCodeCheck() then vbDb2Attach = True else vbDb2Attach = False end if end function '***************************************************************************** ' This function detaches from the db2 instance '***************************************************************************** function vbDb2Detach() WScript.StdOut.Write(program & ".vbDb2Detach()...") if fso.FileExists("db2cmd.log") then fso.DeleteFile("db2cmd.log") end if db2command =("db2 +o -ec -l db2cmd.log detach ") db2cmd.Stdin.WriteLine( db2command ) if vbDb2SqlCodeCheck() then vbDb2Detach = True else vbDb2Detach = False end if end function '***************************************************************************** ' This function connect to the db2 database '***************************************************************************** function vbDb2Connect(database,userid,password) WScript.StdOut.Write(program & ".vbDb2Connect(" & database & ")...") if fso.FileExists("db2cmd.log") then fso.DeleteFile("db2cmd.log") end if if not IsEmpty(password) then db2command = "db2 +o -ec -l db2cmd.log connect to " & database & " user " & userid & " using " & password elseif not IsEmpty(userid) then db2command = "db2 +o -ec -l db2cmd.log connect to " & database & "

Page 26: Db2 Scripting With Windows Scripting Host

user " & userid else db2command = "db2 +o -ec -l db2cmd.log connect to " & database end if db2cmd.Stdin.WriteLine( db2command ) if vbDb2SqlCodeCheck() then vbDb2Connect = True else vbDb2Connect = False end if end function '***************************************************************************** ' This function disconnects from the db2 database '***************************************************************************** function vbDb2ConnectReset() WScript.StdOut.Write(program & ".vbDb2ConnectReset()...") if fso.FileExists("db2cmd.log") then fso.DeleteFile("db2cmd.log") end if db2command =("db2 +o -ec -l db2cmd.log connect reset ") db2cmd.Stdin.WriteLine( db2command ) if vbDb2SqlCodeCheck() then vbDb2ConnectReset = True else vbDb2ConnectReset = False end if end function '***************************************************************************** ' This function performs the database backup '***************************************************************************** function vbDb2BackupDatabase(database,target) WScript.StdOut.Write(program & ".vbDb2BackupDatabase(" & database & ")...") if fso.FileExists("db2cmd.log") then fso.DeleteFile("db2cmd.log") end if if not IsEmpty(target) then db2command = "db2 +o -ec -l db2cmd.log backup database " & database & " to " & target

Page 27: Db2 Scripting With Windows Scripting Host

else db2command = "db2 +o -ec -l db2cmd.log backup database " & database end if db2cmd.Stdin.WriteLine( db2command ) if vbDb2SqlCodeCheck() then vbDb2BackupDatabase = True else vbDb2BackupDatabase = False end if end function '***************************************************************************** ' This function checks for errors in the db2cmd stdout. '***************************************************************************** function vbDb2SqlCodeCheck() linein = db2cmd.StdOut.ReadLine() do while not db2cmd.StdOut.AtEndOfStream linein = db2cmd.StdOut.ReadLine() if len(linein) > 0 then if linein = 0 then WScript.StdOut.WriteLine( "complete, sqlcode=" & linein ) vbDb2SqlCodeCheck = True exit function elseif linein > 0 then WScript.StdOut.WriteLine( "oops, sqlcode=" & linein ) vbDb2SqlCodeCheck = True exit function else WScript.StdOut.WriteLine( "failed, sqlcode=" & linein ) vbDb2SqlCodeCheck = False exit function end if exit do end if WScript.Sleep(250) loop vbDb2SqlCodeCheck = True end function The last function, vbDb2SqlCodeCheck, reads the DB2 Command Window’s standard output to retrieve the SQLCODE returned from the DB2 command that was executed. In this function you could optionally open, read, and parse the log file db2cmd.log created by the DB2 Command Window if a non-zero SQLCODE was encountered.

Scripting scenarios

Page 28: Db2 Scripting With Windows Scripting Host

Now that you’ve learned how DB2 UDB provides interfaces for scripting and how to access these interfaces from Jscript and VBScript from within the Windows Scripting Host (WSH) environment, let’s take a look at some scenarios where you might use a script to automate a task.

DB2 Audit Facility Monitor Script In the first article in this series on DB2 UDB and Windows Scripting we showed you how the DB2 Audit Facility is a utility that can be used to substantially enhance DB2 instance and database security auditing. It is completely managed and controlled by a DB2 system command called <code>db2audit.exe</code>. This command enables you to completely implement very strong DB2 UDB security auditing practices. With this DB2 system command you can configure, start, and stop security auditing. We showed you how to write a script to flush and extract audit data from the facility into a report file. In this article we will expand on this example and show you how you can create Jscript script with WSH that you can periodically schedule to flush the audit log, extract the audit data, and load this data into security audit tables. This task, unscripted would require that you periodically log onto the DB2 server and perform these tasks individually. Before running this script you must first start the DB2 Audit Facility <code>db2audit.exe start</code> and optionally configure the scope and status <code>db2audit.exe configure scope all status both</code>. You will also need to create the DB2 Security Audit tables that will be populated by this script with the data extracted from the DB2 Audit Facility. The DB2 Security Audit table structures are documented in the DB2 UDB Administration Guide. I have provided two DB2 scripts, db2audmon72.ddl and db2audmon81.ddl that you can use to create these tables depending on which version of DB2 Universal Database you are using. For the purpose of this article, you can simply connect to the sample database and run one of these two scripts using <code>db2 –tf db2audmon81.ddl</code> for DB2 UDB v8.1 or <code>db2 –tf db2audmon72.ddl</code> for DB2 UDB v7.2. Note: The DB2 Security Audit table structures have changed slightly in DB2 UDB v8.1 and the current documentation contains an error as to the location of the new column named PACKAGE_VERSION that was added in DB2 UDB v8.1. The output in Example 4 below shows the required and optional parameters displayed in the Windows Shell if the script is invoked without the required parameters. The script requires at the very least the database name and option to be performed, which can be FLUSH, EXTRACT, LOAD, PRUNE, or ALL. The individual options are provided for those who want to perform all of the tasks individually to learn more about the script. An optional userid and password can be supplied to the script, if for example you plan to load the data into a remote database. Example 4. DB2 Audit Monitor script output Microsoft (R) Windows Script Host Version 5.6 Copyright (C) Microsoft Corporation 1996-2001. All rights reserved. db2audmon.wsf: JScript to load DB2 Audit database.

Page 29: Db2 Scripting With Windows Scripting Host

Usage: db2audmonjs.wsf /d:value [/u:value] [/p:value] /o:value Options: d : database. u : userid. p : password. o : options = [FLUSH | EXTRACT | LOAD | PRUNE | ALL]. Example: db2audmon.wsf /d:SAMPLE /o:ALL The script in Listing 19 below consists of several functions to flush, extract, load (into a database), and prune the DB2 Audit Facility logs. Listing 14. DB2 Audit Monitor script <job> <runtime> <description>db2audmon.wsf: JScript to load DB2 Audit database. </description> <named name="d" helpstring="database." type="string" required="true"/> <named name="u" helpstring="userid." type="string" required="false"/> <named name="p" helpstring="password." type="string" required="false"/> <named name="o" helpstring="options = [FLUSH | EXTRACT | LOAD | PRUNE | ALL]." type="string" required="true"/> <example> Example: db2audmon.wsf /d:SAMPLE /o:ALL </example> </runtime> // // Include JScript DB2 Function Library // <script language="JScript" src="jsdb2lib.js"/> // // Main Script // <script language="JScript"> // // Determine if required parameters exist, if not show usage // if (!WScript.Arguments.Named.Exists("d") || !WScript.Arguments.Named.Exists("o")) { WScript.Arguments.ShowUsage(); WScript.Quit(0); } else { // // Initialize global variables // var program = WScript.ScriptName var version = "1.0" WScript.StdOut.WriteLine("**********************************************

Page 30: Db2 Scripting With Windows Scripting Host

*********************************"); WScript.StdOut.WriteLine(program + " Version " + version); WScript.StdOut.WriteLine("*******************************************************************************"); // // Assign arguments to variables // var database = WScript.Arguments.Named("d"); var userid = WScript.Arguments.Named("u"); var password = WScript.Arguments.Named("p"); var option = WScript.Arguments.Named("o"); // // Create db2cmd process // var WshShell = new ActiveXObject("WScript.Shell"); var db2cmd = WshShell.Exec("db2cmd.exe -i "); // // Process options // switch ( option ) { case "FLUSH": // // Flush DB2 Audit Data // var rc = jsDb2AuditFlush(); break; case "EXTRACT": // // Extract DB2 Audit Data // var rc = jsDb2AuditExtract(); break; case "LOAD": // // Connect to database // if (jsDb2Connect(database,userid,password)) { // // Load DB2 Audit Tables // var rc = jsDb2AuditLoad("AUDIT"); var rc = jsDb2AuditLoad("CHECKING"); var rc = jsDb2AuditLoad("CONTEXT"); var rc = jsDb2AuditLoad("OBJMAINT"); var rc = jsDb2AuditLoad("SECMAINT"); var rc = jsDb2AuditLoad("SYSADMIN"); var rc = jsDb2AuditLoad("VALIDATE"); // // Disconnect from database // var rc = jsDb2ConnectReset(); } break; case "PRUNE": //

Page 31: Db2 Scripting With Windows Scripting Host

// Prune DB2 Audit Data // var rc = jsDb2AuditPrune(); break; case "ALL": var rc = jsDb2AuditFlush(); var rc = jsDb2AuditExtract(); if (jsDb2Connect(database,userid,password)) { var rc = jsDb2AuditLoad("AUDIT"); var rc = jsDb2AuditLoad("CHECKING"); var rc = jsDb2AuditLoad("CONTEXT"); var rc = jsDb2AuditLoad("OBJMAINT"); var rc = jsDb2AuditLoad("SECMAINT"); var rc = jsDb2AuditLoad("SYSADMIN"); var rc = jsDb2AuditLoad("VALIDATE"); var rc = jsDb2ConnectReset(); } var rc = jsDb2AuditPrune(); break; default: // // Display usage on invalid option // WScript.Arguments.ShowUsage(); WScript.Echo("ERROR: Invalid option " + option); } // // Terminate and Exit db2cmd process // db2cmd.Stdin.WriteLine("db2 terminate") db2cmd.Stdin.WriteLine("exit") while (db2cmd.Status == 0) { WScript.Sleep(250); } } WScript.Quit(1); //**************************************************************************** // This function flushes db2 audit data to log file //**************************************************************************** function jsDb2AuditFlush() { WScript.StdOut.Write(program+".jsDb2AuditFlush()..."); var db2command =("db2audit.exe flush"); db2cmd.Stdin.WriteLine( db2command ); if (jsDb2AuditCodeCheck()) return 1; else return 0; } //**********************************************************************

Page 32: Db2 Scripting With Windows Scripting Host

****** // This function extract db2 audit data from log file //**************************************************************************** function jsDb2AuditExtract() { WScript.StdOut.Write(program+".jsDb2AuditExtract()..."); var db2command =("db2audit.exe extract delasc"); db2cmd.Stdin.WriteLine( db2command ); if (jsDb2AuditCodeCheck()) return 1; else return 0; } //**************************************************************************** // This function loads db2 audit data from extracted files //**************************************************************************** function jsDb2AuditLoad(table) { WScript.StdOut.Write(program+".jsDb2AuditLoad("+table+")..."); if (fso.FileExists("db2cmd.log")) fso.DeleteFile("db2cmd.log"); if (fso.FileExists(table+".msg")) fso.DeleteFile(table+".msg"); var db2command =("db2 +o -ec -l db2cmd.log import from c:\\sqllib\\db2\\security\\"+table+".del of del modified by chardel0xff messages "+table+".msg insert into audit."+table); db2cmd.Stdin.WriteLine( db2command ); if (jsDb2SqlCodeCheck()) { fso.DeleteFile("c:\\sqllib\\db2\\security\\"+table+".del"); return 1; } else return 0; } //**************************************************************************** // This function prunes db2 audit data from log file //**************************************************************************** function jsDb2AuditPrune() { WScript.StdOut.Write(program+".jsDb2AuditPrune()..."); var db2command =("db2audit.exe prune all"); db2cmd.Stdin.WriteLine( db2command );

Page 33: Db2 Scripting With Windows Scripting Host

if (jsDb2AuditCodeCheck()) return 1; else return 0; } //**************************************************************************** // This function checks for errors in the db2cmd stdout. //**************************************************************************** function jsDb2AuditCodeCheck() { var linein = db2cmd.StdOut.ReadLine(); while (!db2cmd.StdOut.AtEndOfStream) { var linein = db2cmd.StdOut.ReadLine(); if (linein.length > 0) { rc = linein.substr(0,8); if (rc != "AUD0000I") { WScript.StdOut.WriteLine( "failed, rc=" + rc ); var linein = db2cmd.StdOut.ReadLine(); var linein = db2cmd.StdOut.ReadLine(); var linein = db2cmd.StdOut.ReadLine(); return 0; } else { WScript.StdOut.WriteLine( "complete, rc=" + rc ); var linein = db2cmd.StdOut.ReadLine(); break; } } WScript.Sleep(250); } return 1 } </script> </job>

Conclusion In this article we have explored in detail how to write scripts with DB2 UDB in the Windows Scripting Host (WSH) environment. How to create a DB2 Command Window using the use the WSH shell object and invoke DB2 commands and DB2 system commands using both the Run and Execute methods. I also demonstrated how you can use native scripting languages, including Jscript and VBScript, on Windows to automate just about every DB2 UDB Administrative task imaginable. In the next article in this series on DB2 UDB and Windows Scripting we will explore in detail how to write scripts with the Windows Management Instrumentation (WMI) interfaces including the DB2 WMI Provider, available in DB2 UDB v8.1 for Windows, that can be used to manage instances and databases.

Page 34: Db2 Scripting With Windows Scripting Host

About the author Chris Fierros is a DB2 Solutions Expert and principle consultant at Ten Digit Consulting, Inc. (www.tendigit.com), specializing in consulting, training, and support services for DB2 Universal Database. Chris began his career with DB2 on distributed platforms in 1991 at IBM Corporation and has since published articles, presented at conferences, delivered training, and written books about DB2 UDB. Chris is an IBM Certified Solutions Expert (ICSE) in DB2 UDB Administration and DB2 UDB Development as well as an IBM Certified Advanced Technical Expert (CATE) in DB2 Clustering, DB2 Replication, and DB2 Connect. You can reach him at [email protected].