Jython Script to list websphere ports

Posted by Sagar Patil

Following Jython script will return port listings as below.

WASX7357I: By request, this scripting client is not connected to any server process.
Certain configuration and application operations will be available in local mode.
Server name: dmgr
 Node name: Server1_Manager
Port#|EndPoint Name
-----+-------------
 7277|CELL_DISCOVERY_ADDRESS
 9352|DCS_UNICAST_ADDRESS
 9043|WC_adminhost_secure
 9909|BOOTSTRAP_ADDRESS
 8879|SOAP_CONNECTOR_ADDRESS
 9100|ORB_LISTENER_ADDRESS
 9401|SAS_SSL_SERVERAUTH_LISTENER_ADDRESS
 9402|CSIV2_SSL_MUTUALAUTH_LISTENER_ADDRESS
 9403|CSIV2_SSL_SERVERAUTH_LISTENER_ADDRESS
 9060|WC_adminhost

Server name: ihs
 Node name: Server1_Node01

Port#|EndPoint Name
-----+-------------
 90|WEBSERVER_ADDRESS
 9008|WEBSERVER_ADMIN_ADDRESS
#-------------------------------------------------------------------------------
# Name: ListPorts()
# From: WebSphere Application Server Administration using Jython
# Role: Display the Port Numbers configured for each AppServer
# History:
#   date   ver who what
# -------- --- --- ----------------------------------------------------
# 10/11/01 0.3 rag Fix - configIdAsDict()
# 10/10/30 0.2 rag Include showAsDict() so it doesn't need to be imported.
# 09/01/08 0.1 rag Minor cleanup for book
# 04/30/08 0.0 rag New - written for presentation at IMPACT 2008
#-------------------------------------------------------------------------------

import re;
import sys;

try :
 if 'AdminConfig' not in dir() :
 import AdminConfig;
except :
 print 'WebSphere Application Server scripting object unavailable: AdminConfig';
 sys.exit()

#-------------------------------------------------------------------------------
# Name: ListPorts()
# Role: Display all of the configured ports by named EndPoint for each server
#-------------------------------------------------------------------------------
def ListPorts() :
 SEs = AdminConfig.list( 'ServerEntry' ).splitlines();
 #-----------------------------------------------------------------------------
 # for each ServerEntry configuration ID
 #-----------------------------------------------------------------------------
 for SE in SEs :
 seDict = configIdAsDict( SE );
 SEname = seDict[ 'Name' ];
 SEnode = seDict[ 'nodes' ];
 print '''
Server name: %s
 Node name: %s\n
Port#|EndPoint Name
-----+-------------''' % ( SEname, SEnode );
 #---------------------------------------------------------------------------
 # For the given server (SE) get the list of NamedEndPoints
 # Then, for each NamedEndPoint, display the port # and endPointName values
 #---------------------------------------------------------------------------
 for NEP in AdminConfig.list( 'NamedEndPoint', SE ).splitlines() :
 NEPdict = showAsDict( NEP )
 EPdict  = showAsDict( NEPdict[ 'endPoint' ] )
 print '%5d|%s' % ( EPdict[ 'port' ], NEPdict[ 'endPointName' ] )

#-------------------------------------------------------------------------------
# Name: configIdAsDict()
# Role: Convert a configID into a dictionary
#  Fix: "name" can include a hyphen.
#-------------------------------------------------------------------------------
def configIdAsDict( configId ) :
 'configIdAsDict( configId ) - Given a configID, return a dictionary of the name/value components.'
 result  = {};                        # Result is a dictionary
 hier    = [];                        # Initialize to simplifiy checks
 try :                                # Be prepared for an error
 #-----------------------------------------------------------------
 # Does the specified configID match our RegExp pattern?
 # Note: mo == Match Object, if mo != None, a match was found
 #-----------------------------------------------------------------
 if ( configId[ 0 ] == '"' ) and ( configId[ -1 ] == '"' ) and ( configId.count( '"' ) == 2 ) :
 configId = configId[ 1:-1 ];
 mo = re.compile( r'^([-\w ]+)\(([^|]+)\|[^)]+\)$' ).match( configId );
 if mo :
 Name = mo.group( 1 );
 hier = mo.group( 2 ).split( '/' );
 if mo and ( len( hier ) % 2 == 0 ) :
 #---------------------------------------------------------------
 # hier == Extracted config hierarchy string
 #---------------------------------------------------------------
 for i in range( 0, len( hier ), 2 ) :
 name, value = hier[ i ], hier[ i + 1 ];
 result[ name ]  = value;
 if result.has_key( 'Name' ) :
 print '''%s: Unexpected situation - "Name" attribute conflict,
 Name = "%s", Name prefix ignored: "%s"''' % ( funName, result[ 'Name' ], Name );
 else :
 result[ 'Name' ] = Name;
 else :
 print '''configIdAsDict:
 Warning: The specified configId doesn\'t match the expected pattern,
 and is ignored.
 configId: "%(configId)s"''' % locals();
 except :
 ( kind, value ) = sys.exc_info()[ :2 ];
 print '''configIdAsDict: Unexpected exception.\n
 Exception  type: %(kind)s
 Exception value: %(value)s''' % locals();
 return result;

#-------------------------------------------------------------------------------
# Name: showAsDict()
# Role: Convert result of AdminConfig.show( configID ) to a dictionary
#-------------------------------------------------------------------------------
def showAsDict( configID ) :
 'Convert result of AdminConfig.show( configID ) to a dictionary & return it.'
 result = {}
 try :
 #---------------------------------------------------------------------------
 # The result of the AdminConfig.show() should be a string containing many
 # lines.  Each line of which starts and ends with brackets.  The "name"
 # portion should be separated from the associated value by a space.
 #---------------------------------------------------------------------------
 for item in AdminConfig.show( configID ).splitlines() :
 if ( item[ 0 ] == '[' ) and ( item[ -1 ] == ']' ) :
 ( key, value ) = item[ 1:-1 ].split( ' ', 1 )
 result[ key ] = value
 except NameError, e :
 print 'Name not found: ' + str( e )
 except :
 ( kind, value ) = sys.exc_info()[ :2 ]
 print 'Exception  type: ' + str( kind )
 print 'Exception value: ' + str( value )
 return result

#-------------------------------------------------------------------------------
# main entry point
#-------------------------------------------------------------------------------
if ( __name__ == '__main__' ) or ( __name__ == 'main' ) :
 ListPorts();
else :
 print 'This script should be executed, not imported.';

Jython script to Display Websphere Topology

Posted by Sagar Patil

Following Script will display attributes for each configuration item/element displayed at each “level”

def show( hier, here = 0, scope = None ) :
if here < len( hier ) :
pad, Type = here * ‘  ‘, hier[ here ];
for e in AdminConfig.list( Type, scope ).splitlines() :
name  = AdminConfig.showAttribute( e, ‘name’ );
print ‘%s%s : %s ‘ % ( pad, Type, name );
if here < len( hier ) :
show( hier, here + 1, e );
show( [ ‘Cell’, ‘Node’, ‘Server’ ] );

wsadmin>show( [ ‘Cell’, ‘Node’, ‘Server’ ] );
Cell : Server1_Cell
Node : Server1_Manager
Server : dmgr
Node : Server1_Node01
Server : ihs
Server : nodeagent
Server : IHS2
Server : server_member1
Server : server_member2

Jython Scripts for Websphere Administration

Posted by Sagar Patil

Download them from  http://www.ibm.com/developerworks/websphere/library/samples/SampleScripts.html

ex1.py  – Create and modify a server, load an application onto the server, and start the server.
ex2.py  – Reverse of ex1.p1 Stop a server on a given node, uninstalls the given application, and removes the server from the configuration.
ex3.py  – Creates a cluster and starts the server
ex4.py  – Demonstrate the invocation of some useful problem
determination actions involving traces and thread dumps.
ex5.py  – Demonstrate the invocation of various application install commands.
ex6.py  – Produce a short summary of some configuration and runtime information about the WebSphere installation.
ex7.py  – Create a JDBCProvider object using a template.
ex8.py  – Demonstrate J2C Security configuration, including the installation of a J2CResourceAdapter and creation of a J2CConnectionFactory.
ex9.py  – Demonstrate the creation of a JDBCProvider, DataSource and CMPConnectorFactory objects
ex10.py – Demonstrate the creation and use of a variable that is used in the creation of a URLProvider object.
ex11.py – Demonstrate the setting of various port numbers
ex12.py – Demonstrate methods for updating configuration attributes that are lists

Jython script to pull out stats from websphere

Posted by Sagar Patil

Currently I have number of websphere 6.1 instances under RHEL 5.3 but not a tool like hyperic, wily introscope to monitor them actively. I started using wsadmin scripts to pull out stats thru wsadmin.

I am basically trying to get same details thru wsadmin which I could thru NAGIOS plugin. Here is a sample output from NAGIOS.

Monitor JVM heapSize :
JVM heapsize is provided for the entire server. It is measured as: percent used/maximum configured
To Monitor, check_was -s heapsize -w 80 -c 90 -p <server name=””>
[was61@Server1 check_was-0.3]$ ./check_was -s heapsize -w 80 -c 90 -p server_member1
OK – heapsize: 1048576/2097152 (50.0%)|heapsize=50.0%;80;90;

MonitorLiveSessions :
Live session usage can be monitored for the entire server (all hosts) or with a named host. It is measured as: Number of live sessions

[was61@Server1 check_was-0.3]$ ./check_was -s sessions -w 200 -c 400 -p server_member1
OK – live sessions: total 0, default_hostCTI 0, default_hostprsysmgmt 0, default_hostprweb 0, default_hostprdbutil 0|total=0.0;200;400; default_hostcti=0.0;200;400; default_hostprsysmgmt=0.0;200;400; default_hostprweb=0.0;200;400; default_hostprdbutil=0.0;200;400;

MonitorJdbcConnectionPools:
JDBC connection pool usage can be monitored for the entire server (all connection pools) or with a named connection pool. It is measured as: percent used/maximum configured

[was61@Server1 check_was-0.3]$ ./check_was -s connectionpool -w 80 -c 90 -p server_member
OK – connection pool size: Oracle JDBC Driver 5/100 (5.0%)|oraclejdbcdriver=5.0%;80;90;

MonitorThreadPools :
Thread pool usage can be monitored for the entire server (all thread pools) or with a named thread pool. It is measured as: percent used/maximum configured

[was61@Server1 check_was-0.3]$ ./check_was -s threadpool -w 80 -c 90 -p server_member1
CRITICAL – thread pool size: WebContainer 4/100 (4.0%), SoapConnectorThreadPool 3/5 (60.0%), SIBFAPInboundThreadPool 0/50 (0.0%), HAManager.thread.pool 2/2 (100.0%), MessageListenerThreadPool 0/50 (0.0%), ORB.thread.pool 0/50 (0.0%), SIBFAPThreadPool 2/50 (4.0%), ProcessDiscovery 1/2 (50.0%), TCPChannel.DCS 3/20 (15.0%)|webcontainer=4.0%;80;90; soapconnectorthreadpool=60.0%;80;90; sibfapinboundthreadpool=0.0%;80;90; hamanager_thread_pool=100.0%;80;90; messagelistenerthreadpool=0.0%;80;90; orb_thread_pool=0.0%;80;90; sibfapthreadpool=4.0%;80;90; processdiscovery=50.0%;80;90; tcpchannel_dcs=15.0%;80;90;</server>

Attached is a python script which will return similar results
Purpose: wsadmin script used to display user specified information about
         WebSphere Application Server resources.\n
Version: %(version)s
Updated: %(updated)s\n
  Usage: %(cmdName)s [options]\n
Required switches/options:
  -i | --info       <value> = Type of information being requested
  -s | --serverName <value> = Target serverName\n
Optional switches/options:
  -n | --nodeName   <value> = Target nodeName\n
Information types/values:
  connectionpool - Display Connection Pool details
  heapsize       - Display Heap Size details
  threadpool     - Display Thread Pool details
  sessions       - Display Session Details\n
Notes:
- Long form option values may be separated/delimited from their associated
  identifier using either a space, or an equal sign ('=').\n
- Short form option values may be sepearated from their associated letter
  using an optional space.\n
- Text containing blanks must be enclosed in double quotes.\n
Examples:
  wsadmin -f %(cmdName)s.py -i heapsize -s server1 -n node01\n'''
[was61@Server1 was_scripts]$ /opt/IBM/WebSphere/AppServer/profiles/Profile01/dmgr/bin/wsadmin.sh -f /home/was61/was_scripts/check_was.py -i heapsize -s Server1  server_member2
WASX7209I: Connected to process “dmgr” on node Server1_Manager using SOAP connector;  The type of process is: DeploymentManager
WASX7303I: The following options are passed to the scripting environment and are available as arguments that are stored in the argv variable: “[-i, heapsize, -s, Server1server_member2]”
heapsize: node=Server1_Node01  server=Server1server_member2  used=1027.2 MB (65.69%)  free=536.5 MB
[was61@ was_scripts]$ /opt/IBM/WebSphere/AppServer/profiles/Profile01/dmgr/bin/wsadmin.sh -f /home/was61/was_scripts/check_was.py -i threadpool -s  server_member2
WASX7209I: Connected to process “dmgr” on node Server1_Manager using SOAP connector;  The type of process is: DeploymentManager
WASX7303I: The following options are passed to the scripting environment and are available as arguments that are stored in the argv variable: “[-i, threadpool, -s, server_member2]”
|             Low    High
|           Water  Water  Lower  Upper  Current
Name | integral  Mark   Mark   Bound  Bound  Usage    Ratio
————————+—————————————————–
Message.Listener.Pool |      0.0   10     10     10     50      0      0.00%
ORB.thread.pool |      0.0   10     10     10     50      0      0.00%
SIBFAPInboundThreadPool | 9090637.0    1      4      4     50      3     75.00%
SIBFAPThreadPool | 112975.0    1      4      4     50      2     50.00%
TCPChannel.DCS | 255726.0    1      5      5     20      3     60.00%
WebContainer | 12011409.0    1     10     10     50      7     70.00%
So here  “WebContainer | 12011409.0   1  10  10  50   7  70.00%” means WebContainer currently using 7 processes out of 10 allocated and they can expand upto 50 MAX.

Websphere : Jython script to return performance matrix details of Node

Posted by Sagar Patil

Here is a Jython script to return performance matrix detail of a node for following details :
Free and used JVM heap size,
Free and used Thread pools,
Free and used JDBC connection pools
Free and used Live sessions

[was61@Server1 .scripts]$ wsadmin.sh -f check_was.py -i heapsize -s  Server_member1

WASX7209I: Connected to process “dmgr” on node Server1_Manager using SOAP connector;  The type of process is: DeploymentManager
WASX7303I: The following options are passed to the scripting environment and are available as arguments that are stored in the argv variable: “[-i, heapsize, -s, Server_member1]”
heapsize: node=Server1_Node01  server=Server_member1  used=1024.0 MB (52.44%)  free=928.6 MB

Download script from http://www.oracledbasupport.co.uk/wp-content/uploads/2010/08/Check-was Python Script.txt

The Jython script used is as below :

#———————————————————————-
# File Name: check_was.py
#   Purpose: Display user requested information about
#            WebSphere Application Server (WSAS) resources.
#
# Run “$WAS_HOME/Dmgr/bin/wsadmin.sh -conntype none -lang jython”
# wsadmin>print AdminConfig.list(‘Server’);
# dmgr(cells/Server1_Cell/nodes/Server1_Manager/servers/dmgr|server.xml#Server_1)
# ihs-prpc(cells/Server1_Cell/nodes/Server1_Node01/servers/ihs-prpc|server.xml#Server_1280149489851)
# server_member1(cells/Server1_Cell/nodes/Server1_Node01/servers/server_member1|server.xml#Server_1280159031517)
# server_member2(cells/Server1_Cell/nodes/Server1_Node01/servers/server_member2|server.xml#Server_1280159031764)
# nodeagent(cells/Server1_Cell/nodes/Server1_Node01/servers/nodeagent|server.xml#Server_1120677326772)
#
#———————————————————————-
”’Command: %(cmdName)s\n
Purpose: wsadmin script used to display user specified information about
WebSphere Application Server resources.\n
Usage: %(cmdName)s [options]\n
Required switches/options:
-i | –info       <value> = Type of information being requested
-s | –serverName <value> = Target serverName\n
Optional switches/options:
-n | –nodeName   <value> = Target nodeName\n
Information types/values:
connectionpool – Display Connection Pool details
heapsize       – Display Heap Size details
threadpool     – Display Thread Pool details
sessions       – Display Session Details\n
\nNotes:
– Long form option values may be separated/delimited from their associated
identifier using either a space, or an equal sign (‘=’).\n
– Short form option values may be sepearated from their associated letter
using an optional space.\n
– Text containing blanks must be enclosed in double quotes.\n
Examples:
wsadmin -f %(cmdName)s.py -i heapeize -s server1 -n node01\n”’

import os, re, sys, getopt;

__scriptName__ = ‘check_was’;
__version__    = ‘0.1’;
__updated__    = ’22 July 2010′;

#———————————————————————
# Name: localMode()
# Role: Return true (1) if AdminControl object is unavailable, false
#       (0) otherwise.
# Note: In localmode (i.e., -conntype none), this returns true (1)
#———————————————————————
def localMode() :
‘localMode() – Return true (1) if AdminControl object is unavailable, false (0) otherwise’
try :
host   = AdminControl.getCell();
result = 0;                        # No, we’re connected
except :
result = 1;                        # Yes, –contype none
return result;

#———————————————————————
# Name: beanNameAsDict()
# Role: Parse the specified MBean and return a dictionary of the name
#       value pairs
#———————————————————————
def beanNameAsDict( bean ) :
‘beanNameAsDict() – Parse the specified MBean and return a dictionary of the name value pairs’
result = {};
for pair in bean.split( ‘:’, 1 )[ 1 ].split( ‘,’ ) :
n, v = pair.split( ‘=’, 1 );
result[ n ] = v;
return result;

#———————————————————————
# Name: callerName
# Role: Utility routine used to determine, and return the name of the
#       calling function.
# Note: Dependends on sys._getframe()
#  See: http://code.activestate.com/recipes/66062/
#———————————————————————
def callerName() :
“callerName() – Returns the name of the calling routine (or ‘?’)”
return sys._getframe( 1 ).f_code.co_name;

#———————————————————————
# Name: configurable()
# Role: Return true (1) if AdminConfig object is available, false (0) otherwise
#———————————————————————
def configurable() :
‘configurable() – Return true (1) if AdminConfig object is available, false (0) otherwise’
try :
host   = AdminConfig.list( ‘Server’ );
result = 1;                        # True  = AdminConfig object is available
except :
result = 0;                        # False = AdminConfig object not available
return result;

#———————————————————————
# Name: configIdAsDict
# Role: Parse a config ID and return a dictionary of name/value pairs
# Note: Exception handler requires sys module
#       The keys in the returned dictionary come from the configID, so
#       are unlikely to match your defect expectations about exactly
#       what values are used (e.g., ‘nodes’ instead of “Node”)
#———————————————————————
def configIdAsDict( configId ) :
‘configIdAsDict( configId ) – Given a configID, return a dictionary of the name/value components.’
funName = callerName();              # Name of this function
result  = {};                        # Result is a dictionary
hier    = [];                        # Initialize to simplifiy checks
try :                                # Be prepared for an error
#—————————————————————–
# Does the specified configID match our RegExp pattern?
# Note: mo == Match Object, if mo != None, a match was found
#—————————————————————–
if ( configId[ 0 ] == ‘”‘ ) and ( configId[ -1 ] == ‘”‘ ) and ( configId.count( ‘”‘ ) == 2 ) :
configId = configId[ 1:-1 ];
mo = re.compile( r’^([\w ]+)\(([^|]+)\|[^)]+\)$’ ).match( configId );
if mo :
Name = mo.group( 1 );
hier = mo.group( 2 ).split( ‘/’ );
if mo and ( len( hier ) % 2 == 0 ) :
#—————————————————————
# hier == Extracted config hierarchy string
#—————————————————————
for i in range( 0, len( hier ), 2 ) :
( name, value ) = hier[ i ], hier[ i + 1 ];
result[ name ]  = value;
if result.has_key( ‘Name’ ) :
print ”’%s: Unexpected situation – “Name” attribute conflict,
Name = “%s”, Name prefix ignored: “%s””’ % ( funName, result[ ‘Name’ ], Name );
else :
result[ ‘Name’ ] = Name;
else :
print ”’%(funName)s:
Warning: The specified configId doesn\’t match the expected pattern,
and is ignored.
configId: “%(configId)s””’ % locals();
except :
( kind, value ) = sys.exc_info()[ :2 ];
print ”’%(funName)s: Unexpected exception.\n
Exception  type: %(kind)s
Exception value: %(value)s”’ % locals();
return result;

#———————————————————————
# Name: heapsize()
# Role: Display information about the heap for the specified server
#———————————————————————
def heapsize( configID ) :
‘heapsize() – Display used and free stats for the JVM of the specified server’
cDict = configIdAsDict( configID );
jvm   = AdminControl.queryNames( ‘type=JVM,process=%(servers)s,node=%(nodes)s,*’ % cDict );
if jvm :
used    = AdminControl.getAttribute( jvm, ‘heapSize’ );
free    = AdminControl.getAttribute( jvm, ‘freeMemory’ );
total   = int( used ) + int( free );
percent = float( used ) * 100.0 / float( total );
print ‘heapsize: node=%s  server=%s  used=%.1f MB (%.2f%%)  free=%.1f MB’ % ( cDict[ ‘nodes’ ], cDict[ ‘servers’ ], MB( used ), percent, MB( free ) );
else :
print ‘Specified server does not appear to be active: node=%(nodes)s  server=%(servers)s’ % cDict;

#———————————————————————
# Name: localMode()
# Role: Return true (1) if AdminControl object is unavailable, false
#       (0) otherwise.
# Note: In localmode (i.e., -conntype none), this returns true (1)
#———————————————————————
def localMode() :
‘localMode() – Return true (1) if AdminControl object is unavailable, false (0) otherwise’
try :
host   = AdminControl.getCell();
result = 0;                        # No, we’re connected
except :
result = 1;                        # Yes, –contype none
return result;

#———————————————————————
# Name: main()
# Role: Perform the actual work of the script
#———————————————————————
def main( cmdName = None ) :
missingParms = ‘%(cmdName)s: Insufficient parameters provided.\n’;
ambigServer  = ‘%(cmdName)s: Ambiguous server specified: %(serverName)s\n’;
badReqdParam = ‘%(cmdName)s: Invalid required parameter: %(key)s\n’;
badInfo      = ‘%(cmdName)s: As yet unimplemented “info” request: %(info)s\n’;
badNode      = ‘%(cmdName)s: Unknown node: %(nodeName)s\n’;
badServer    = ‘%(cmdName)s: Unknown server: %(serverName)s\n’;
serverReqd   = ‘%(cmdName)s: Missing required parameter: “serverName”.\n’;

if not cmdName :
cmdName = __scriptName__;

#——————————————————————-
# How many user command line parameters were specified?
#——————————————————————-
argc = len( sys.argv );                   # Number of arguments
if ( argc < 2 ) :                         # If too few are present,
print missingParms % locals();          #   tell the user, and
Usage( cmdName );                       #   provide the Usage info
else :                                    # otherwise
Opts = parseOpts( cmdName );            #   parse the command line

#——————————————————————-
# Assign values from the user Options dictionary, to make value
# access simplier, and easier.  For example, instead of using:
#   Opts[ ‘nodeName’ ]
# we will be able to simply use:
#   nodeName
# to access the value.
#——————————————————————-
for key in Opts.keys() :
val = Opts[ key ];
cmd = ‘%s=Opts[“%s”]’ % ( key, key );
#   print cmd;
exec( cmd );

#——————————————————————-
# Check required parameters
#——————————————————————-
if info not in [ ‘heapsize’, ‘sessions’, ‘connectionpool’, ‘threadpool’ ] :
print badInfo % locals();
Usage( cmdName );

if not serverName :
print serverReqd % locals();
Usage( cmdName );

#——————————————————————-
# Was the nodeName specified, and if so, does it exist?
#——————————————————————-
node = None;
if nodeName :
for nid in AdminConfig.list( ‘Node’ ).splitlines() :
if nid.startswith( nodeName + ‘(‘ ) :
node = nid;
if not node :
print badNode % locals();

#——————————————————————-
# Does the specified serverName exist (within the scope of the
# specified node)?
# Note: A scope of None is identical to not specifying a scope
#——————————————————————-
servers = [];
for sid in AdminConfig.list( ‘Server’, node ).splitlines() :
if sid.startswith( serverName + ‘(‘ ) :
servers.append( sid );
if len( servers ) < 1 :
print badServer % locals();
sys.exit();
elif len( servers ) > 1 :
print ambigServer % locals();
nodes = [];
for sid in servers :
nodes.append( configIdAsDict( sid )[ ‘nodes’ ] );
print ‘Specify one of the following nodes using the –nodeName option: ‘ + ( ‘, ‘.join( nodes ) );
sys.exit();
server = servers[ 0 ];

# print ‘Request for %s on %s’ % ( info, server );
if info == ‘heapsize’ :
heapsize( server );
else :
print ‘Not yet implemented: “%s”‘ % info

#———————————————————————
# Name: MB()
# Role: Convert the specified (integer) value [bytes] into MegaBytes
#———————————————————————
def MB( val ) :
‘MB() – Convert specified integer (byte) value into MegaBytes’
return int( val ) / ( 1024.0 * 1024.0 );

#———————————————————————
# Name: parseOpts()
# Role: Process the user specified (command line) options
#———————————————————————
def parseOpts( cmdName ) :
shortForm = ‘i:n:s:’;
longForm  = ‘info=,nodeName=,serverName=’.split( ‘,’ );
badOpt    = ‘%(cmdName)s: Unknown/unrecognized parameter%(plural)s: %(argStr)s\n’;
optErr    = ‘%(cmdName)s: Error encountered processing: %(argStr)s\n’;
problem   = ‘%(cmdName)s: Error option processing problem: %(opt)s\n’;

try :
opts, args = getopt.getopt( sys.argv, shortForm, longForm );
except getopt.GetoptError :
argStr = ‘ ‘.join( sys.argv );
print optErr % locals();
Usage( cmdName );

#——————————————————————-
# Initialize the Opts dictionary using the longForm key identifiers
#——————————————————————-
Opts = {};
for name in longForm :
if name[ -1 ] == ‘=’ :
name = name[ :-1 ]
Opts[ name ] = None;

#——————————————————————-
# Process the list of options returned by getopt()
#——————————————————————-
for opt, val in opts :
if opt in   ( ‘-i’, ‘–info’ )       : Opts[ ‘info’       ] = val
elif opt in ( ‘-n’, ‘–nodeName’ )   : Opts[ ‘nodeName’   ] = val
elif opt in ( ‘-s’, ‘–serverName’ ) : Opts[ ‘serverName’ ] = val
else :
print problem % locals();

#——————————————————————-
# Check for unhandled/unrecognized options
#——————————————————————-
if ( args != [] ) :        # If any unhandled parms exist => error
argStr = ‘ ‘.join( args );
plural = ”;
if ( len( args ) > 1 ) : plural = ‘s’;
print badOpt % locals();
Usage( cmdName );

#——————————————————————-
# Return a dictionary of the user specified command line options
#——————————————————————-
return Opts;

#———————————————————————
# Name: Usage()
# Role: Display usage information necessary to use this script.
#———————————————————————
def Usage( cmdName = None ) :
if not cmdName :
cmdName = __scriptName__;

print __doc__ % locals();       # Script docstring contains usage info
sys.exit();

#———————————————————————-
# Code execution begins
#———————————————————————-
if ( __name__ == ‘__main__’ ) or ( __name__ == ‘main’ ) :
if localMode() :
print ‘A connection to WebSphere Application Server is required.\n’;
Usage();
elif configurable() :
main();
else :
print ‘WebSphere Application Server scripting objects appear to be unavailable.\n’;
Usage();
else :
print ‘This script should be executed, not imported.\n’;
Usage( __name__ );


Jython Script : Get websphere Server Details

Posted by Sagar Patil

This jython script will produce output  as below :

$/opt/IBM/WebSphere/AppServer/bin/wsadmin.sh -lang jython -profile serverStatus.py -c “serverStatus()”

WASX7209I: Connected to process “dmgr” on node server1_Manager using SOAP connector;  The type of process is: DeploymentManager

Server               |        Cell       |         Node         | Status
——————–+——————-+———————-+——–
dmgr                | Server1_Cell | Server1_Manager | running
server_member1         | Server1_Cell | Server1_Node01  | running
server_member2 | Server1_Cell | Server1_Node01  | running
nodeagent           | Server1_Cell | Server1_Node01  | running

import re;

#———————————————————————
# Name: serverStatus()
# Role: Display the status of the known servers
#———————————————————————
def serverStatus() :
#——————————————————————-
# RegExp to extract the server, cell, and node name for each server
#——————————————————————-
pat = re.compile( r’^(\w+)\(cells/(\w+)/nodes/(\w+)/servers\/\1.*\)$’ );

#——————————————————————-
# Retrieve the list of known servers
# While building the list, compute the max length of each name
#——————————————————————-
info   = [];
maxLen = [ 0 ] * 3;

#——————————————————————-
# For each server of the known servers
#——————————————————————-
servers = AdminConfig.list( ‘Server’ ).splitlines();
for server in servers :
#—————————————————————–
# An Object Name will exist if the specified server is running
#—————————————————————–
oName = AdminConfig.getObjectName( server );
if oName != ” :
status = ‘running’;
else :
status = ‘stopped’;
#—————————————————————–
# Extract the server, cell, and node name
# (match Object)
#—————————————————————–
mObj = pat.match( server );
if mObj :
#—————————————————————
# Save the data, and see if the length of each field name is the
# longest we have yet seen (i.e., maxLen[ i ])
#—————————————————————
( sName, cName, nName ) = mObj.groups();
info.append( ( sName, cName, nName, status ) );
for i in range( 3 ) :
L = len( mObj.group( i + 1 ) );
if L > maxLen[ i ] : maxLen[ i ] = L;

#——————————————————————-
# Display the information
#——————————————————————-
( L0, L1, L2 ) = maxLen;
( sName, cName, nName, status ) = ‘Server,Cell,Node,Status’.split( ‘,’ );
sName = sName.center( L0 );
cName = cName.center( L1 );
nName = nName.center( L2 );
print ‘%(sName)s | %(cName)s | %(nName)s | %(status)s’ % locals();
print ( ‘-‘ * L0 ) + ‘-+-‘ + ( ‘-‘ * L1 ) + ‘-+-‘ + ( ‘-‘ * L2 ) + ‘-+——–‘;
for scn in info :
( sName, cName, nName, status ) = scn;
print ‘%-*s | %-*s | %-*s | %s’ % ( L0, sName, L1, cName, L2, nName, status );

Top of Page

Top menu