Monday, August 24, 2020

Custom Password Generator tool and Weblogic Embedded LDAP automated password reset

**The tool is a custom one created for use in my current organization, by myself. Copyright lies with me.**

This tool creates a random password, pulls the e-mail IDs of users from database, resets the user's passwords and notifies them over email.

This is specific to Oracle CC&B application using embedded LDAP authentication.

Components of the Tool:

Files-----------------------

file.properties: Properties file

user.txt: User ID list

words.txt: Random words that'll be used to generate the passwords

punct.txt: Special characters

get_email.sql: PL/SQL query to fetch user's email ID from database table

Scripts---------------------

Password_generator.py

append.sh


Script Body

-----------------------------------------------------------------------------------------------------------------------

#Script created by Debomitra Roy, to create password

from java.io import FileInputStream

print ("############Custom script to generate random passwords will start now#############")

print ("#####################Script created by Debomitra Roy for SEWA#####################")

propInputStream = FileInputStream("file.properties")

configProps = Properties()

configProps.load(propInputStream)

import os

string = configProps.get("stringfile")

inputfile = configProps.get("inputfile")

punct =  configProps.get("punct")

userfile =  configProps.get("userfile")

efile=configProps.get("efile")

subjecta=configProps.get("subjecta")

subjectb=configProps.get("subjectb")

subjectc=configProps.get("subjectc")

subjectd=configProps.get("subjectd")

me=configProps.get("from")

domainName=configProps.get("domain.name")

adminURL=configProps.get("admin.url")

connect(url=adminURL,userConfigFile='/ouaf/cissys/debo_scripts/Reset_pass_user/keyfile/uatuserconfigfile.secure',userKeyFile='/ouaf/cissys/debo_scripts/Reset_pass_user/keyfile/uatuserkeyfile.secure')

os.system("sed -e '/^$/d' user.txt > user1.txt")

os.system("sort user1.txt| uniq -u > modified_user.txt")

fin=open(inputfile)

for line in fin.readlines():

  words = line.split()

  count = len(line.split())

  count1 = 0

  while(count1<count):

   for word in words:

     p=open(punct)

     for spl in p.readlines():

         spcl = spl.split()

         spcl=spcl[count1]

         word1 = word[-2]

         word2 = word[-3]

         word3 = word[0]

         word4 = word[-1]

         pas= word4 + word2 + word3 + word1 + spcl

         file_object = open('pass.txt', 'a+')

         data = file_object.read(100)

         file_object.write(pas)

         file_object.write("\n")

         file_object.close()

         count1+=1

  else:

   print "Complete"

os.system('mv passstring.txt ./backup/passstring.txt_old')

usr=open(userfile)

i=1

for lin in usr.readlines():

 each = lin.strip()

 i+=1

 tail=each[-3:]

 file_object = open('passstring.txt', 'a+')

 file_object.write(tail)

 file_object.write("\n")

 file_object.close()

os.system('sh append.sh')

print "########Passwords have been generated########"

print ("############Custom script to reset passwords will start now#############")

print ("#####################Script created by Debomitra Roy for SEWA#####################")

fin=open(efile)
for line in fin.readlines():
  words = line.split()
  atnr=cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
  atnr.resetUserPassword(words[0],words[2])
  import smtplib
  msga = subjecta + " " + words[0] + " " + subjectb
  msgb = subjectc + " " + words[2]
  sub = ("High importance: %s\r\n\r\n%s\r\n\r\n%s\r\n(This is a system generated message)\r\n" %(msga, msgb, subjectd))
  mailid=words[1]
  s = smtplib.SMTP('localhost')
  s.sendmail(me, [mailid], sub)
  print "Password for user ID " + words[0] + " has been reset and communicated to user at " + mailid
  s.quit()
else:
  print "Complete"
os.system('sh flag.sh')
os.system('rm -f email.txt')
print "List of ID and passwords removed"
print "Copyright: Debomitra Roy"
disconnect()


append.sh

------------------------------------------------------------------------------------------------------------------

#!/bin/bash

count=`cat passstring.txt|wc -l`

i=1

count=$count+1

x=`ls passwords.txt`

d=`date +"%d_%m_%Y`

mv $x ./backup/passwords.txt_d

while [  $i -lt $count ]; do

 id=`sed -n "$i p" passstring.txt`

 wrd=`sed -n "$i p" pass.txt`

 str2=$wrd$id

 i=$(($i+1))

 echo $str2 >> passwords.txt

done

####Get email ID####

sort user.txt|uniq -d > check.txt

if [ -s check.txt ]

then

 echo "Duplicate values are there, check in file. Duplicate values will be skipped."

 mailx -s "Check duplicates in user list" debomitra.roy@sewa.gov.ae < /ouaf/cissys/debo_scripts/Reset_pass_user/module_uat/check.txt

else

 echo "File is empty, no duplicate values"

fi

count=`cat modified_user.txt|wc -l`

count=$count+1

i=1

x=`ls modified_user.txt`

mv email.txt ./backup/email.txt_d

while [  $i -lt $count ]; do

 mid=`sed -n "$i p" modified_user.txt`

 #echo $mid

 sqlplus -S usermod/usermod@CCBTEST @get_email.sql $mid > output.log

 eid=`tail -2 output.log|head -1`

 strng="no rows selected"

 if [ "$eid" = "$strng" ];

 then

  echo "No email ID found for user ID $mid, will skip writing output to file"

  #echo "Skip" >> email.txt

 else

  pass=`sed -n "$i p" passwords.txt`

  echo $mid $eid $pass >> email.txt

  echo "Email ID written to file successfully"

 fi

 i=$(($i+1))

done

exit 0


Tuesday, September 11, 2018

Passion for Python

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


  1. domain.properties: A properties file
  2. menu.sh: An user interactive menu driven shell script that has the individual scripts plugged to it: 
  3. gridlinkds_xa.sh and create_XAGridLinkds.py: Shell script that calls the respentive Python script to create a XA enabled Grid Link DS.
  4. gridlinkds_nonxa.sh and create_XAGridLinkds.py: Shell script that calls the respective Python script to create a non-XA enabled Grid Link DS.
  5. 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.
  6. 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.
  7. health.sh and jvm_health.py: Shows JVM healths
  8. deployments.sh and deployment_tasks.py: Shell script that calls the respective Python script to list all existing applications deployed and updates selected applications.
Contents of scripts:

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)