Feb 1, 2018

EMCLI @ script mode - python script examples

Example-1: List Linux Targets

# Source Code List Targets
if (len(sys.argv) <> 1 ):
    print "Usage: emcli @list_targets.py OSname"
    exit()
login( username="gouranga", password="password")
myDBs = list( resource="Targets", search="TARGET_TYPE='oracle_database'" )            
for DB in myDBs.out()['data']:
    # we get the host info for the oracle database target
    hostinfo = list( resource="Targets",
    search="TARGET_NAME='" + DB['HOST_NAME'] + "'" )
    # the above one should return only one item, so we use the first item
    OS = hostinfo.out()['data'][0]['TYPE_QUALIFIER1']
    # we print only the targets if their OS name equal to the first argument of script
    if ( OS.lower() == sys.argv[0].lower() ):
        print DB['TARGET_NAME'],hostinfo.out()['data'][0]['TYPE_QUALIFIER1']

# End of script list_targets.py

How to Run?
e.g., emcli @list_targets.py linux

The above script will show the target details as passed the operating system type. In the script I used password. But this can be ignored for security reason for production quality. if ignored, then @ run time password to be inserted. You can change username or you can change the script little bit so that both username and password will be prompted.

Example-2: Create Bulk users with various Roles

# source code 
#################################################
# Creating bulk users with passing x.csv file   #
# Created Date  : 02-Feb-2018                   #
# Created by    : Gouranga Mohapatra            #
################################################# 
# source code to create bulk users with different roles
# Sample EMCLI Python script file to create users
# check number of arguments
if len(sys.argv) <> 1:
    print "Usage: emcli @create_bulk_users.py userslist.csv"
    exit()
# login to OMS
#
lg = login( username="gouranga" )
if lg.exit_code() <> 0:
    print lg.error()
# open file for reading
#
f = open( sys.argv[0], 'r' ) 
# loop for each line of the file
#
for line in f:
    # split line to list (array)
    #
    sp = line.split(',')
    #
    # create user, save the file name as description
    #
    create_user( name=sp[0], password=sp[1], roles=sp[2],
    desc="Listed in " + sys.argv[0])
# End of script

Note : The script accepts only one argument (the name of the CSV file containing the information of new users. The arguments can be accessed via sys.argv object. Then it logins to OMS (it will ask the password of SYSMAN/ Super Admin. You can modify the script and add your EM administrator username and password.

Here’s the sample CSV file (userslist.csv):

Test11,oracle,em_all_operator
test12,oracle,EM_ALL_VIEWER
test13,oracle,EM_CLOUD_ADMINISTRATOR
test14,oracle,em_all_designer

How to Run?
$ emcli @create_bulk_users.py filename.csv

Now you can use below command to view whether your users created or not?

$ emcli list -resource="Administrators" -columns="USER_NAME,REPOS_ACCOUNT_STATUS"

Example-3: CREATE BLACKOUT FOR MULTIPLE TARGETS ON EM13C

Sometimes you may need to blackout all or group of targets due to some emergency outage like power failures or storage level activities. So it is very difficut to do one by one blackouts. In otherhand, The notifications emails of a “planned” downtime is one of the annoying things of monitoring systems. You forget creating blackout and you start a maintenance work, and you get lots of notifications mails. Most of the time, the target which goes down, also affect other targets so it will multiple the number of unwanted notifications mails. Good thing is, it’s very easy to create blackouts on EM13c. We can do it through web console, emctl or emcli tools. A one-liner is enough for it:

$ emctl start blackout BlackOutName -nodeLevel  

The above code will create a blackout for the all targets on the server. We can achieve the same thing by EMCLI:

For single targets, you can do like below:

$ emcli create_blackout -name="BlackOutName" -reason="imergency outage" -add_targets="server_name:host" -propagate_targets 
   -schedule="duration:-1" # indefinite  

If we use emcli, we have more options such as creating repeating blackouts, entering a reason for blackout, enabling blackout for a group of targets (which resides on different hosts). What if we need to create blackout for multiple targets. As I mentioned, EMCLI can be used to create blackout for groups. We can create groups on  EM13c, and instead of passing names of all targets in a group, we can give the group name:

# source code 
#################################################
# Blackout for group of targets                 #
# Created Date  : 02-Feb-2018                   #
# Created by    : Gouranga Mohapatra            #
################################################# 
# Example EMCLI Python script file to create blackout for multiple targets
#
# check number of arguments
if len(sys.argv) <> 2:
    print "Usage to start a blackout: emcli @multiblackout.py targets.csv blackout_name"
    print "Usage to stop a blackout: emcli @multiblackout.py stop blackout_name"
    exit()

blackout_name = sys.argv[1].upper()

# login to OMS
login( username="SYSMAN", password="yoursupersecretpassword" )

if sys.argv[0].lower() == "stop":
    stop_blackout( name= blackout_name )
    # comment below line to keep old blackouts
    delete_blackout( name = blackout_name )
    print "%s blackout stopped and deleted." % blackout_name
    exit()

# open file for reading
f = open( sys.argv[0], 'r' )

# variable to keep all targets
alltargets = ""

# loop for each line of the file
for target in f:
    # build alltargets string
    alltargets += target.replace("\n","") + ";"

create_blackout( name = blackout_name, add_targets=alltargets, reason=blackout_name, schedule="duration:-1" )
# End of script

The script accepts two parameters. First parameter is the path of the file containing the targets, the second parameter is the name of the blackout.

The targets file should be something like this:

e.g., targets.csv
hcmdb:oracle_database  
obiee:oracle_database  
example01:host

After you create a blackout, you can stop (and delete) the blackout by running it again, but this time you need to enter “stop” as the file name:

-- start blackout
$./emcli @multiblackout.py /u01/OEM/scripts/mytargets.csv TESTBLACKOUT   
$./emcli @multiblackout.py stop TESTBLACKOUT 

-- Stop blackout
$./emcli @multiblackout.py /u01/OEM/scripts/mytargets.csv TESTBLACKOUT   
$./emcli @multiblackout.py stop TESTBLACKOUT 

You can do error handling in the script for more efficient.

Example-4 : Delete All Named Credentials:

When you want to delete all the created named credentials by as administrator, then you need a loop to collect all the NC and delete them which are owned by the same administrator.

Here I am writing a shell script this time.

e.g.,

$ cat deleteNC.sh

#!/bin/bash
#################################################
# delete all your Named Credentials             #
# Created Date  : 10-Feb-2018                   #
# Created by    : Gouranga Mohapatra            #
################################################# 

export EMCLI_HOME=/u01/app/OEM/Middleware13c
export PATH=$PATH:$EMCLI_HOME/bin
export LOG_HOME=/u01/app/OEM/backup/log
export DATE=`date +%d%m%y_%H%M%S`

echo -n "Enter OEM Username:"
read USERNAME
echo -n "Enter password:"
read -s PWD
echo ""
echo "Authonticating..."
echo ""
(
login=$(emcli login -username=$USERNAME -password=$PWD | grep -c "successful")
if [ $login -eq 1 ]; then
  echo "Login Succeeded..."
  echo "Finding Named Credentials..."
  echo "Listing and Deleteing Named Credentials for user "$USERNAME
  echo ""
  for CN in $(emcli list_named_credentials -script -noheader | cut -f1);
 do
        echo $CN
        emcli delete_named_credential -cred_name="$CN"
 done
 emcli logout
fi
) 2>&1 | tee ${LOG_HOME}/delete_NC_${USERNAME}_${DATE}.log

How to Run?

$./deleteNC.sh

Disclaimer : Run  these scripts at your own risk.


Click here to See more scripts.



4 comments:

  1. Hi, do you have sample script to create group and add targets by using phyton?

    ReplyDelete
  2. I'm working with your multiblackout.py script and I am trying to figure out how to add -propagate_targets and/or -full_blackout_all_hosts to the line below.

    create_blackout( name = blackout_name, add_targets=alltargets, reason=blackout_name, schedule="duration:-1" )

    Is it possible to add those types of parameters to that command line?

    Thank you,
    Phil

    ReplyDelete
  3. Excellent post. You have shared some wonderful tips. I completely agree with you that it is important for any blogger to help their visitors. Once your visitors find value in your content, they will come back for more How to Run Python Program In Script Mode



    ReplyDelete

Translate >>