I had been toying around with Python scripting to create a module that helps automate certain weblogic tasks. The scripts are shared below, copyright myself :)
domain.properties
- domain.properties: A properties file
- menu.sh: An user interactive menu driven shell script that has the individual scripts plugged to it:
- gridlinkds_xa.sh and create_XAGridLinkds.py: Shell script that calls the respentive Python script to create a XA enabled Grid Link DS.
- gridlinkds_nonxa.sh and create_XAGridLinkds.py: Shell script that calls the respective Python script to create a non-XA enabled Grid Link DS.
- userloop.sh and create_usersloop.py: Shell script that calls the respective Python script to create multiple users using loop. All users names will be incremented by a number, example:Test1,Test2,and so on and passwords will be the same as user name.
- user_file.sh and create_users.py: Shell script that calls the respective Python script to create multiple users using a .csv file containing comma separated user names.
- health.sh and jvm_health.py: Shows JVM healths
- deployments.sh and deployment_tasks.py: Shell script that calls the respective Python script to list all existing applications deployed and updates selected applications.
domain.properties
#Properties file created for automation by Debomitra Roy :)
domain.name=auto_domain
admin.url=t3://localhost:8600
admin.userName=weblogic
admin.password=ouafadmin1
#security.realmName=myrealm
total.username=1
create.user.name=test
create.user.password=test
create.user.description= This is a Training User
group.name=Administrators
file.name=myfile.txt
ds.name=TestDS
ds.jndi.name=jdbc/TestDS
ds.url=jdbc:oracle:thin:@//<IP>:<PORT>:<SID>
ds.driver=oracle.jdbc.OracleDriver
ds.xadriver=oracle.jdbc.xa.client.OracleXADataSource
ds.username=<username>
ds.password=<password>
ds.target.type=Cluster
ds.target.name=auto_cluster
menu.sh
#!/bin/bash
# A menu driven Shell script
echo " M A I N - M E N U"
echo "1. Create XA Grid Link Data source"
echo "2. Create Non-XA Grid Link Data source"
echo "3. Create User in Weblogic realm"
echo "4. Check JVM runtime health"
echo "5. Create User in Weblogic realm using file"
echo "6. List/update deployed applications"
echo "7. Exit"
echo -n "Please enter option: "
read opt
case $opt in
1) echo " Creating XA Grid Link Data Source";
./gridlinkds_xa.sh
;;
2) echo " Creating Non-XA Grid Link Data Source";
./gridlinkds_nonxa.sh
;;
3) echo " Creating User in Weblogic Realm";
./userloop.sh
;;
4) echo " Checking JVM runtime health";
./health.sh
;;
5) echo " Creating User in Weblogic Realm using file";
./user_file.sh
;;
6) echo " All deployed applications will be listed and selected deployments will be deployed";
./deployments.sh
;;
7) echo "Bye $USER";
exit 1;;
*) echo "$opt is an invaild option. Please select option between 1-7 only";
echo "Press [enter] key to continue. . .";
read enterKey
./menu.sh
;;
esac
gridlinkds_xa.sh
#!/bin/bash
#Script created by Debomitra Roy
old_pwd=`pwd`
echo "Enter Domain Home location: "
read i
cd $i
cd bin/
. ./setDomainEnv.sh
cd $old_pwd
java weblogic.WLST create_XAGridLinkds.py
cd $old_pwd
./menu.sh
create_XAGridLinkds.py
#Script created by Debomitra Roy
from java.io import FileInputStream
propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminURL=configProps.get("admin.url")
adminUserName=configProps.get("admin.userName")
adminPassword=configProps.get("admin.password")
#dsName=configProps.get("ds.name")
#dsJNDIName=configProps.get("ds.jndi.name")
#dsURL=configProps.get("ds.url")
dsDriver=configProps.get("ds.xadriver")
#dsUsername=configProps.get("ds.username")
#dsPassword=configProps.get("ds.password")
dsTargetType=configProps.get("ds.target.type")
dsTargetName=configProps.get("ds.target.name")
#Connect to the AdminServer.
connect(adminUserName, adminPassword, adminURL)
dsName=raw_input('Enter Grid Link Data Source Name: ')
#print" Data source Name entered is: ", dsName
#dsJNDIName=raw_input('Enter Grid Link Data Source JNDI Name: ')
#print" Data source JNDI Name entered is: ", dsJNDIName
dsURL=raw_input('Enter JDBC Connection URL: ')
#print" JDBC Connection URL entered is: ",dsURL
dsUsername=raw_input('Enter Username: ')
#print" Username entered is: ",dsUsername
dsPassword=raw_input('Enter Password: ')
#print" Password entered is: ",dsPassword
name="jdbc/"
dsJNDIName=name+dsName
check=raw_input(' Continue? Y/N : ')
if check == "Y":
edit()
startEdit()
# Create data source.
cd('/')
cmo.createJDBCSystemResource(dsName)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName)
cmo.setName(dsName)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDataSourceParams/' + dsName)
set('JNDINames',jarray.array([String(dsJNDIName)], String))
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName)
cmo.setUrl(dsURL)
cmo.setDriverName(dsDriver)
set('Password', dsPassword)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCConnectionPoolParams/' + dsName)
cmo.setTestTableName('SQL SELECT 1 FROM DUAL\r\n\r\n')
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName + '/Properties/' + dsName)
cmo.createProperty('user')
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName + '/Properties/' + dsName + '/Properties/user')
cmo.setValue(dsUsername)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDataSourceParams/' + dsName)
cmo.setGlobalTransactionsProtocol('TwoPhaseCommit')
cd('/SystemResources/' + dsName)
set('Targets',jarray.array([ObjectName('com.bea:Name=' + dsTargetName + ',Type=' + dsTargetType)], ObjectName))
save()
activate()
disconnect()
#exit()
else:
print" Exiting operation"
disconnect()
#exit()
create_NonXAGridLinkDS.py
from java.io import FileInputStream
propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminURL=configProps.get("admin.url")
adminUserName=configProps.get("admin.userName")
adminPassword=configProps.get("admin.password")
#dsName=configProps.get("ds.name")
#dsJNDIName=configProps.get("ds.jndi.name")
#dsURL=configProps.get("ds.url")
dsDriver=configProps.get("ds.driver")
#dsUsername=configProps.get("ds.username")
#dsPassword=configProps.get("ds.password")
dsTargetType=configProps.get("ds.target.type")
dsTargetName=configProps.get("ds.target.name")
#Connect to the AdminServer.
connect(adminUserName, adminPassword, adminURL)
dsName=raw_input('Enter Grid Link Data Source Name: ')
#print"Data source Name entered is: ", dsName
#dsJNDIName=raw_input('Enter Grid Link Data Source JNDI Name: ')
#print"Data source JNDI Name entered is: ", dsJNDIName
dsURL=raw_input('Enter JDBC Connection URL: ')
#print"JDBC Connection URL entered is: ",dsURL
dsUsername=raw_input('Enter Username: ')
#print"Username entered is: ",dsUsername
dsPassword=raw_input('Enter Password: ')
#print"Password entered is: ",dsPassword
name="jdbc/"
dsJNDIName=name+dsName
check=raw_input('Continue? Y/N : ")
if check=="Y":
edit()
startEdit()
# Create data source.
cd('/')
cmo.createJDBCSystemResource(dsName)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName)
cmo.setName(dsName)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDataSourceParams/' + dsName)
set('JNDINames',jarray.array([String(dsJNDIName)], String))
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName)
cmo.setUrl(dsURL)
cmo.setDriverName(dsDriver)
set('Password', dsPassword)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCConnectionPoolParams/' + dsName)
cmo.setTestTableName('SQL SELECT 1 FROM DUAL\r\n\r\n')
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName + '/Properties/' + dsName)
cmo.createProperty('user')
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName + '/Properties/' + dsName + '/Properties/user')
cmo.setValue(dsUsername)
cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDataSourceParams/' + dsName)
cmo.setGlobalTransactionsProtocol('None')
cd('/SystemResources/' + dsName)
set('Targets',jarray.array([ObjectName('com.bea:Name=' + dsTargetName + ',Type=' + dsTargetType)], ObjectName))
save()
activate()
disconnect()
else:
disconnect()
create_users.py
#Script created by Debomitra Roy, to read a text file containing comma separated user names and creating those users in weblogic realm
from java.io import FileInputStream
propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminURL=configProps.get("admin.url")
adminUserName=configProps.get("admin.userName")
adminPassword=configProps.get("admin.password")
realmName=configProps.get("security.realmName")
totalUsers_to_Create=configProps.get("total.username")
userName=configProps.get("create.user.name")
userPassword=configProps.get("create.user.password")
userDescription=configProps.get("create.user.description")
groupName=configProps.get("group.name")
connect(adminUserName, adminPassword, adminURL)
check=raw_input ('Do all the users to be created belong to same Group? Y/N :')
if check=="N":
fname = raw_input ('Enter name of file containing comma separated user list in .csv format: ')
f=open(fname)
print "You selected file: ", fname
ask = raw_input ('Proceed? : Y/N ')
if ask=="Y":
try:
for line in f.readlines():
items = line.split(',')
for item in items:
try:
print 'Creating User',item.strip()
atnr=cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
atnr.createUser(item.strip(), item.strip(),userDescription)
except:
print 'User',item.strip(),'already exists'
continue
try:
print 'User',item.strip(),'to be added to group'
gname=raw_input ('Enter Group name for user :')
print 'Adding User',item.strip(),'to group',gname
atnr.addMemberToGroup(gname,item.strip())
#break
except:
print 'Invalid group',gname, 'please enter correct group'
gname=raw_input ('Enter Group name for user :')
print 'Adding User',item.strip(),'to group',gname
atnr.addMemberToGroup(gname,item.strip())
except Exception, e:
print e
disconnect()
else:
#group=raw_input ('Enter User group: ')
atnr=cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
tries = 0
while tries < 3:
group = raw_input('Enter User group: ')
if atnr.groupExists(group):
#print "Group input: ",group
break
print "Incorrect Group, please enter correct User group. 3 attepmts allowed"
tries += 1
if atnr.groupExists(group):
print "Group entered is: ",group
else:
print "Incorrect Group,multiple invalid inputs were made. Exiting application"
disconnect()
exit()
#try:
#if atnr.groupExists(group):
# print "Group input: ",group
#else:
# group=raw_input ('Incorrect Group, please enter correct User group: ')
#except:
# group=raw_input ('Incorrect Group, please enter correct User group: ')
# continue
file = raw_input ('Enter name of file containing comma separated user list in .csv format: ')
f=open(file)
print "You selected file: ", file
ask = raw_input ('Proceed? : Y/N ')
if ask=="Y":
try:
for line in f.readlines():
items = line.split(',')
for item in items:
try:
print 'Creating User',item.strip()
atnr=cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
atnr.createUser(item.strip(), item.strip(),userDescription)
except Exception, e:
print 'User',item.strip(),'already exists'
continue
try:
print 'User',item.strip(),'to be added to group'
print 'Adding User',item.strip(),'to group',group
atnr.addMemberToGroup(group,item.strip())
except:
print 'Invalid group',group, 'please enter correct group'
gname=raw_input ('Enter Group name for user :')
print 'Adding User',item.strip(),'to group',gname
atnr.addMemberToGroup(gname,item.strip())
except Exception, e:
print e
create_usersloop.py
#Script created by Debomitra Roy to create users in weblogic
from java.io import FileInputStream
propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminURL=configProps.get("admin.url")
adminUserName=configProps.get("admin.userName")
adminPassword=configProps.get("admin.password")
realmName=configProps.get("security.realmName")
#totalUsers_to_Create=configProps.get("total.username")
#userName=configProps.get("create.user.name")
#userPassword=configProps.get("create.user.password")
#userDescription=configProps.get("create.user.description")
#groupName=configProps.get("group.name")
connect(adminUserName, adminPassword, adminURL)
totalUsers_to_Create=raw_input('Enter number of users to create: ')
userName=raw_input('Enter user name. Ex: If name entered is Test and number of users are 2, users will be created in format Test1,Test2.: ')
userPassword=raw_input('Enter password. Ex: If password entered is Pass and number of users are 2, passwords will be created in format Pass1,Pass2.: ')
userDescription=raw_input('Enter user description: ')
groupName=raw_input('Enter group name: ')
print "Users will be created in default security realm and assigned to Default Authenticator provider"
check=raw_input('Continue? Y/N : ')
if check=="Y":
from weblogic.management.security.authentication import UserEditorMBean
print "Creating users ..."
atnr=cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
x=1
while (x <= int(totalUsers_to_Create)):
try:
atnr.createUser(userName +str(x), userPassword +str(x), userDescription +str(x))
print " Created user: ", userName +str(x)
except:
print " Already Exists..."
x = x + 1
#print "Created users successfully"
print "Adding created users to group ..."
atnr=cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
x=1
while (x <= int(totalUsers_to_Create)):
try:
atnr.addMemberToGroup(groupName , userName +str(x))
print "Group associated to users:" , userName +str(x)
except:
print " Incorrect group..."
x = x + 1
disconnect()
#exit()
else:
print "Exiting operation "
disconnect()
#exit()
jvm_health.py
from java.io import FileInputStream
propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminURL=configProps.get("admin.url")
adminUserName=configProps.get("admin.userName")
adminPassword=configProps.get("admin.password")
#realmName=configProps.get("security.realmName")
def serverStatus(server):
cd('/ServerLifeCycleRuntimes/' + server.getName())
return cmo.getState()
connect(adminUserName, adminPassword, adminURL)
realmName=cmo.getSecurityConfiguration().getDefaultRealm()
authProvider = realmName.getAuthenticationProviders()
#print"Default Security Realm name is :",realmName
#print"Authentication providers are ",authProvider
servers = cmo.getServers()
domainRuntime()
for server in servers:
serverState = serverStatus(server)
serverName = server.getName()
print '**************************************************\n'
print '############## ', serverName, '###############'
print '**************************************************\n'
print '##### Server State #####', serverState
print '##### Server ListenPort #####', server.getListenPort()
# print '##### Server Health State #####', server.getHealthState()
# print '##### Server Heap Size Current ###', totalMemory
domainRuntime()
servers = domainRuntimeService.getServerRuntimes();
print('################################################################')
print('# Java heap information per server')
print('################################################################')
print('%20s %10s %8s %8s %4s' % ('Server','Current','Free','Max','Free'))
for server in servers:
free = int(server.getJVMRuntime().getHeapFreeCurrent())/(1024*1024)
freePct = int(server.getJVMRuntime().getHeapFreePercent())
current = int(server.getJVMRuntime().getHeapSizeCurrent())/(1024*1024)
max = int(server.getJVMRuntime().getHeapSizeMax())/(1024*1024)
print('%20s %7d MB %5d MB %5d MB %3d%%' % (server.getName(),current,free,max,freePct))
disconnect()
deployment_tasks.py
#Script written by Debomitra Roy
from java.io import FileInputStream
propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminURL=configProps.get("admin.url")
adminUserName=configProps.get("admin.userName")
adminPassword=configProps.get("admin.password")
realmName=configProps.get("security.realmName")
def serverStatus(server):
cd('/ServerLifeCycleRuntimes/' + server.getName())
return cmo.getState()
connect(adminUserName, adminPassword, adminURL)
servers = cmo.getServers()
domainRuntime()
print 'List of JVMs are: '
for server in servers:
serverName = server.getName()
print serverName
if server.getCluster()!=None:
clustername=server.getCluster().getName()
print 'Server ',serverName,'belongs to cluster', clustername
print ' '
#listApplications()-----------------Lists all applications deployed
#print 'All applications that are deployed currently are being listed below'
domainConfig()
print '##############All applications that are deployed currently are being listed below##############'
apps=cmo.getAppDeployments()
for appName in apps:
domainConfig()
cd ('/AppDeployments/'+appName.getName()+'/Targets')
loc=getMBean('/AppDeployments/'+appName.getName()+'/Targets')
appID=loc.getApplicationIdentifier()
print '#########################################################################'
print ' Application: ',appID
print '#########################################################################'
print ' '
print 'Target :'
target = ls(returnMap='true')
cd('domainRuntime:/AppRuntimeStateRuntime/AppRuntimeStateRuntime')
state = cmo.getIntendedState(appName.getName())
print 'Current state: '
print state
print ' '
#Function to define exception
def WhenExcept(i):
#i=1
#print '#################Only 2 more attempts allowed before exiting'
i=2
while i>0:
try:
print '#################Only',i,'more attempts allowed before exiting'
app=raw_input('Enter application to be updated: ')
print '######################Updating file',app,'########################'
edit()
startEdit()
cd('/AppDeployments/'+app)
apploc=cmo.getAbsoluteSourcePath()
print 'Location of application',app,'is',apploc
updateApplication(app,apploc)
save()
activate()
disconnect()
except:
print 'Incorrect application name'
print 'Please enter correct application name'
#print '#################Only',i,'more attempts allowed before exiting'
i-=1
# stopEdit('y')
exit('y')
#Update application module
i=input('How many applications need to be updated? Please enter integer value: ')
if i>1:
print 'Options to provide application names: '
print 'Enter option:'
print '1> File of .csv format containing comma separated list of applications to be updated.'
print '2> Input name of application files individually.'
ask=input('Input choice 1/2 : ')
if ask==1:
fname=raw_input('Enter file name: ')
f=open(fname)
try:
for line in f.readlines():
items = line.split(',')
for item in items:
try:
print '######################Updating file',item.strip(),'########################'
edit()
startEdit()
cd('/AppDeployments/'+item.strip())
#apploc=cmo.getAbsoluteSourcePath(item.strip())
apploc=cmo.getAbsoluteSourcePath()
print 'Location of application',item.strip(),'is',apploc
updateApplication(item.strip(),apploc)
save()
activate()
# disconnect()
except:
print 'Incorrect application name,please rectify in .csv file'
continue
except:
print 'blah'
else:
try:
app=raw_input('Enter application to be updated: ')
print '######################Updating file',app,'########################'
edit()
startEdit()
cd('/AppDeployments/'+app)
apploc=cmo.getAbsoluteSourcePath()
print 'Location of application',app,'is',apploc
updateApplication(app,apploc)
save()
activate()
disconnect()
except:
print 'Incorrect application name'
print 'Please enter correct application name'
WhenExcept(2)
else:
try:
app=raw_input('Enter application to be updated: ')
print '######################Updating file',app,'########################'
edit()
startEdit()
cd('/AppDeployments/'+app)
apploc=cmo.getAbsoluteSourcePath()
print 'Location of application',app,'is',apploc
updateApplication(app,apploc)
save()
activate()
disconnect()
except:
print 'Incorrect application name'
print 'Please enter correct application name'
WhenExcept(2)
No comments:
Post a Comment