fhg
Volume 8, Number -- May 14, 2008

Use PCOMM Scripts to Execute Remote PC Commands, Part 1

Published: May 14, 2008

by Michael Sansoterra

Over the years, much has been published in the AS/400 and System i community about how to execute remote commands on a PC from a 5250 emulation session using a variety of homegrown or IBM utilities. Most of the methods I have seen presented are good but require a fair bit of knowledge for installation, port numbers to open for the Windows XP firewall, calling an API from a high-level language program to retrieve the emulator workstation's IP address and the like.

For those who use Windows and iSeries Access (now System i Access) or IBM's Personal Communications (PCOMM) emulator product, I'd like to revisit an alternative and powerful technique that can allow remote command execution without additional software or configuration.

This technique involves writing VBScript that can be executed from within the emulator. If you don't know the VBScript language, don't worry as only a few lines of code are needed to execute a remote command. Keep in mind that VBScript can do much more than execute a Windows OS command. VBScript can also create Excel documents, Word documents, access the PC or network file system, read and write text files, access a remote database, call a Web service, etc. The possibilities are endless! Therefore, these PCOMM scripts allow for more than just remote command execution--they allow for remote program execution using just about any Windows library that is accessible as a Component Object Model (COM) or ActiveX object.

Before we look at code, keep in mind that the emulator used by the iSeries Access and Personal Communications emulator products are accessible programmatically as ActiveX objects. This means that the VBScript code written to execute from within the emulator can also access the emulator's screen via this API. This is powerful because a script can be written to read one or more values on the current screen, which allows for context sensitive commands on the PC without having to modify the application source code. This is a plus for those who use canned applications without source or who want to minimize application modifications.

For an overview of this technique, see Data Entry Robots. Please note this article presents Visual Basic for Applications (VBA) code, which is similar to VBScript shown here, but not entirely equivalent.

On To Coding...

Now we'll learn how to write one of these PCOMM scripts. To create a PCOMM script, choose Edit→Preferences→Macro/Script. (Editor's Note: On some versions of Client Access, choose Assist→Macro/Script Setup.) The Macro/Script Setup window will appear. Click the Customize button. When the Customize Macro/Script window appears, choose File→New→VB Script. In this example, we'll write a VBScript macro to execute a hypothetical batch command script called AppScript.cmd that exists on the local PC. Enter the following VBScript code in the Script Statements portion of the window:

Dim wsh
Set wsh=CreateObject("WScript.Shell")
wsh.Run("%windir%\AppScript.cmd")
wsh.Popup "Done"

When done entering the script, choose File→Save As and save the code under the file name of your choice, such as RunAppScript.mac. The default extension is .MAC.

If you open the .MAC file with a text editor such as notepad, the full script will look like this:

[PCOMM SCRIPT HEADER]
LANGUAGE=VBSCRIPT
DESCRIPTION=Remote Command Demo
[PCOMM SCRIPT SOURCE]
Dim wsh
Set wsh=CreateObject("WScript.Shell")
wsh.Run("%windir%\AppScript.cmd")
wsh.Popup "Done"

Honestly, the editor that comes with the 5250 emulator is abysmal in terms of features. It would be nice to have a line counter, basic syntax checking, and a search and replace option. I normally develop my code in a VBA environment (such as Excel or Access) first, and then convert the code to VBScript so that I spend as little time as possible within the PCOMM editor.

So if you decide to write VBScript code totally outside the PCOMM editor you will have to add the following four lines manually to your script:

[PCOMM SCRIPT HEADER]
LANGUAGE=VBSCRIPT
DESCRIPTION=Type your description here
[PCOMM SCRIPT SOURCE]

As you can see, the [PCOMM SCRIPT HEADER] section declares the macro scripting language (as far as I know, only VBScript works--I tried JavaScript but couldn't get it to work) and the description of the macro. The description is important as it gives a little note to the user about what the macro does. The [PCOMM SCRIPT SOURCE] section, as its name implies, contains the actual VBScript code.

Execute the Macro

When your macro is done and placed in the user's macro folder, the user can run the macro by choosing Actions→Start Playing Macro/Script. The user will then be prompted to select a macro name from the list, so name your macros wisely. Your macros should end with a .MAC extension for PCOMM to recognize them.

Explaining the VBScript Code

Let's examine these four lines of code to find out how this thing works.

Dim wsh
Set wsh=CreateObject("WScript.Shell")
wsh.Run("%windir%\AppScript.cmd")
wsh.Popup "Done"

To execute a Windows command in VBScript all we need to do is create a WScript.Shell object and then execute its "Run" method. To define a variable in VBScript we simply use the Dim statement. Please note that VBScript does not allow data types to be explicitly assigned to a variable. (The statement "Dim i as Integer" is invalid in VBScript.) We then use the CreateObject command to create an instance of the WScript.Shell command.

In the example, the Run method executes the specified command script. (A .cmd file is basically a newer alternative to the old DOS .bat files that is available under the Windows NT class operating systems.) The %WinDir% environment variable, which is a standard Windows environment variable, will be expanded to the actual windows folder when the script runs so that a path doesn't need to be hardcoded. Technically, if your script is within the PC's default "path" variable then the full path to the script is not needed; just specifying AppScript.cmd will be enough because Windows is smart enough to search the path (similar to the library list). Finally, the Popup method shows a message box to the user.

The WShell's run method is powerful indeed, being similar to the Windows START command. Besides just searching the path for you, it is also smart enough to open documents for registered extension types such as .XLS, .DOC, .TXT, .PDF files, etc. without the script specifying the associated application's path on the PC. So, if you pass the Run method the value "\\Server1\Documents\AppManual.pdf," Acrobat Reader will automatically start (assuming the Reader it is installed on your system). However, if my memory serves, this "document search" feature may not work on older Windows 9x systems.

What else can the Run method do? It can execute a URL string, such as:

  • http://google.com
  • mailto:mycustomer@custdomain.com
  • file://\\servername\shared
  • ftp://ftp.software.ibm.com/as400/products/clientaccess/win32/
    v5r4m0/servicepack/si27741/

All this is great because it means that we can easily start an email draft (on a system that has an appropriate email client), open a local or network folder for browsing, or start a Web browser session with a few lines of code.

A Slight Detour Through PCOMM's HotSpot Functionality

Let me regress for a minute to a lesser known feature of PCOMM. Depending on the application, URLs aren't such a big deal because the PCOMM emulator itself can execute them with a double click. In other words, if you have the text mailto:mycustomer@custdomain.com or http://google.com anywhere on your 5250 screen, all the user has to do is double click on the text and the corresponding PC application will open for the URL. (Make sure that the "Execute URL" option is enabled under the emulator's Edit→Preferences→Hotspots menu option. It should be enabled by default.)

So, if you have room on your screen for small URLs, don't even bother with VBScript, just let PCOMM do the work!

Back to VBScript and URLs

However, VBScript will probably be needed for large URLs like this:

http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0
&sort_by=status&Requester=UPSHome&term_warn=yes&tracknums_displayed=5
&AgreeToTermsAndConditions=yes&TypeOfInquiryNumber=T&loc=en_US&
InquiryNumber1=1Z4700480348000110&InquiryNumber2=&Inq

That is, unless you have the luxury of taking up precious 5250 screen space with this garble or on occasions when a URL has an embedded space. In these cases a script can help.

Working with Screen Values Within the Script

As mentioned earlier, the real power of the script can be leveraged by using the PCOMM presentation space object (see Data Entry Robots) to read data on the 5250 application screen to use when building the URL. This way the tracking number can be extracted from the current screen at the specified row and column, and then placed as a parameter to your batch file, or in this example, in a URL:

[PCOMM SCRIPT HEADER]
LANGUAGE=VBSCRIPT
DESCRIPTION=Shipment Tracking
[PCOMM SCRIPT SOURCE]

Dim wsh
Set wsh=CreateObject("WScript.Shell")

Dim pComm5250
'
' URL to Website
'
Const UPS_URL="http://wwwapps.ups.com/WebTracking/processInputRequest?
HTMLVersion=5.0&sort_by=status&Requester=UPSHome&term_warn=yes&tracknums_
displayed=5&AgreeToTermsAndConditions=yes&TypeOfInquiryNumber=T&loc=en_US&
InquiryNumber1=$TRACKINGNO$&InquiryNumber2=&Inq"
'
' Get Presentation Space of current emulator window
'
autECLSession.SetConnectionByName(ThisSessionName)
Set pComm5250=autECLSession.autECLPS
'
' Extract Shipment tracking number from screen
'
Dim TrackingNo
TrackingNo=pComm5250.GetText(20,7,20)

If Left(TrackingNo,2)= "1Z" Then
    Dim Url
    '
    ' Insert Extracted Tracking Number into URL
    '
    url=Replace(UPS_URL, "$TRACKINGNO$",TrackingNo)
    wsh.Run(Url)
Else
    wsh.Popup "Invalid UPS Tracking #"
End If

Set wsh=Nothing
Set pComm5250=Nothing

The autECLSession variable is automatically made available to the script courtesy of the emulator. This object will allow code to access the presentation space, operator information area and other aspects of the emulator. The pComm5250 variable is important here as it represents the PCOMM presentation space object. This little gem allows the script to read and write to the 5250 screen as needed. The GetText method demonstrated in the example is used to retrieve the UPS tracking number from the screen at row 20, column 7 for 20 characters.

This is the one problem area with this kind of "screen scraping." The scripts will have to change if the coordinates of your screen fields change. Additionally, since you can query values on the screen, you can easily expand the script to identify FedEx vs. UPS vs. USPS tracking numbers and build an appropriate URL.

Tips for Working with Macros

When using the macro/script feature, keep the following in mind:

  • Make sure to bulletproof the VBScript code using the ON ERROR command and checking the Err object appropriately. I've seen certain script failures cause the emulator itself to terminate!
  • Often each script will be written specifically for one or more application screens. Therefore the script should do some checking to make sure there is a specific field name or literal text present on the screen (such as a title or program name) before allowing the script to run. For example, you probably don't want a script designed to retrieve a tracking number and then start a Web browser session to run from the WRKJOB or WRKSPLF system screens!
  • To prevent users from having too many macros available to choose from, consolidate macros for multiple screens where possible. For example, if you write a macro against a 5250 screen containing address information for the purpose of opening a URL to MapQuest.com, where possible, enable this macro to work with multiple 5250 screens instead of writing individual macros for each screen.
  • If you have more than a few users, a network drive should probably be used to share all scripts in a common place (such as a public folder) that is accessible to all users. Otherwise you'd have to distribute each script to each user's PC. By default, my iSeries Access installation stores its macro/script files in the "C:\program files\ibm\Client Access\Emulator\private" folder. Not something you want to tinker with for everyone. To set a different default macro/script folder, choose Edit→Preferences→Macro/Script. When the Macro/Script Setup window appears, enter a new default folder in the "Macro\Script Directory" box.
  • Use the Popup method, MsgBox command, or some other indicator to notify the user when the macro has completed successfully. Unfortunately, VBScript isn't GUI friendly so basic message and input boxes are about all that is available.

As you can see, the PCOMM script mechanism provides a full featured and powerful alternative to traditional remote command processing. Of course there are a few trade-offs, but the benefits are plentiful. In the next tip, I'll demonstrate VBScript code that will read a database file and create an Excel document on the fly when the user runs a macro. Even if you don't know VBScript you'll be able to easily tailor the code to your own needs.


RELATED RESOURCES

Microsoft's VBScript Documentation

Windows 2000 Command Reference



                     Post this story to del.icio.us
               Post this story to Digg
    Post this story to Slashdot


Sponsored By
WORKSRIGHT SOFTWARE

Do you need area code information?
Do you need ZIP Code information?
Do you need ZIP+4 information?
Do you need city name information?
Do you need county information?
Do you need a nearest dealer locator system?

We can HELP! We have affordable AS/400 software and data to do all of the above. Whether you need a simple city name retrieval system or a sophisticated CASS postal coding system, we have it for you!

The ZIP/CITY system is based on 5-digit ZIP Codes. You can retrieve city names, state names, county names, area codes, time zones, latitude, longitude, and more just by knowing the ZIP Code. We supply information on all the latest area code changes. A nearest dealer locator function is also included. ZIP/CITY includes software, data, monthly updates, and unlimited support. The cost is $495 per year.

PER/ZIP4 is a sophisticated CASS certified postal coding system for assigning ZIP Codes, ZIP+4, carrier route, and delivery point codes. PER/ZIP4 also provides county names and FIPS codes. PER/ZIP4 can be used interactively, in batch, and with callable programs. PER/ZIP4 includes software, data, monthly updates, and unlimited support. The cost is $3,900 for the first year, and $1,950 for renewal.

Just call us and we'll arrange for 30 days FREE use of either
ZIP/CITY or PER/ZIP4.

WorksRight Software, Inc.
Phone: 601-856-8337
Fax: 601-856-9432
E-mail: software@worksright.com
Web site: www.worksright.com


Senior Technical Editor: Ted Holt
Technical Editor: Joe Hertvik
Contributing Technical Editors: Edwin Earley, Brian Kelly, Michael Sansoterra
Publisher and Advertising Director: Jenny Thomas
Advertising Sales Representative: Kim Reed
Contact the Editors: To contact anyone on the IT Jungle Team
Go to our contacts page and send us a message.

Sponsored Links

Vibrant Technologies:  The leading source for IBM Power Systems and Upgrades
COMMON:  Join us at the Focus 2008 workshop conference, October 5 - 8, in San Francisco, California
Vision Solutions:  System i Management Tips Blog - Free i5/OS Tips Each Week!


 

IT Jungle Store Top Book Picks

Easy Steps to Internet Programming for AS/400, iSeries, and System i: List Price, $49.95
Getting Started with PHP for i5/OS: List Price, $59.95
The System i RPG & RPG IV Tutorial and Lab Exercises: List Price, $59.95
The System i Pocket RPG & RPG IV Guide: List Price, $69.95
The iSeries Pocket Database Guide: List Price, $59.00
The iSeries Pocket Developers' Guide: List Price, $59.00
The iSeries Pocket SQL Guide: List Price, $59.00
The iSeries Pocket Query Guide: List Price, $49.00
The iSeries Pocket WebFacing Primer: List Price, $39.00
Migrating to WebSphere Express for iSeries: List Price, $49.00
iSeries Express Web Implementer's Guide: List Price, $59.00
Getting Started with WebSphere Development Studio for iSeries: List Price, $79.95
Getting Started With WebSphere Development Studio Client for iSeries: List Price, $89.00
Getting Started with WebSphere Express for iSeries: List Price, $49.00
WebFacing Application Design and Development Guide: List Price, $55.00
Can the AS/400 Survive IBM?: List Price, $49.00
The All-Everything Machine: List Price, $29.95
Chip Wars: List Price, $29.95


 
The Four Hundred
The i Platform Roadmap Is a Work in Progress

IBM Loses Two Key Executives to Retirement--Really

Java Performance Is OS Agnostic on Power6 Gear

As I See It: Soothing the Savage Programmer

IBM Goes Stateless and Cooler with iDataPlex Servers

The Linux Beacon
AMD Revises Opteron Roadmaps, Pushes Out Rev Gs

New and Updated Barcelona Boxes Debut from Sun

Java Performance Is OS Agnostic on Power6 Gear

As I See It: Soothing the Savage Programmer

Virtual Server Sprawl Reeled In with Tideway Foundation 7.1

Four Hundred Stuff
Aldon Responds to Business Pressures on IT Departments

Former Magic CEO Sues as iBOLT Sales Channel Widened

MKS Updates Change Management for i OS, Warns of Big Revenue Jump

INGENICA Updates Universal Print Driver

Original Software Now Supports Mainframe in TestDrive-Assist

Big Iron
The Modern Mainframe: A Model of Space and Energy Efficiency

Top Mainframe Stories From Around the Web

Chats, Webinars, Seminars, Shows, and Other Happenings

System i PTF Guide
May 3, 2008: Volume 10, Number 18

April 26, 2008: Volume 10, Number 17

April 19, 2008: Volume 10, Number 16

April 12, 2008: Volume 10, Number 15

April 5, 2008: Volume 10, Number 14

March 29, 2008: Volume 10, Number 13

The Windows Observer
Microsoft Withdraws Yahoo Bid, Won't Go Hostile

GDCM Seeks to 'Defrag' the Data Center for Higher Efficiency

Hey ASA: Microsoft Delivers New Automated Service Agent

The X Factor: Everybody Wants Citrix Systems?

SugarCRM Supports Smart Phones, Including Windows Mobile

The Unix Guardian
Sun Delivers OpenSolaris Development Distro, Plus Support

AMD Revises Opteron Roadmaps, Pushes Out Rev Gs

IBM Loses Two Key Executives to Retirement--Really

GDCM Seeks to 'Defrag' the Data Center for Higher Efficiency

Power Systems: The Feeds and Speeds

Four Hundred Monitor
Four Hundred Monitor's
Full iSeries Events Calendar

THIS ISSUE SPONSORED BY:

ProData Computer Services
WorksRight Software
COMMON


Printer Friendly Version


TABLE OF CONTENTS
Writing Secure PHP Applications

Use PCOMM Scripts to Execute Remote PC Commands

Admin Alert: Things to Do When Adding Drives to a System

Four Hundred Guru

BACK ISSUES

From the IT Jungle Forums
Java Messages

Restrict *cmd to specific user

Copying recs from a subfile to a file and keeping highlights

Imbedded SQL

CPYFRMSTMF problem

CPYTOIMPF problem





 
Subscription Information:
You can unsubscribe, change your email address, or sign up for any of IT Jungle's free e-newsletters through our Web site at http://www.itjungle.com/sub/subscribe.html.

Copyright © 1996-2008 Guild Companies, Inc. All Rights Reserved.
Guild Companies, Inc., 50 Park Terrace East, Suite 8F, New York, NY 10034

Privacy Statement