LDAP Search Script

From PeformIQ Upgrade
Jump to navigation Jump to search

Python Implementation

#!/usr/bin/env python
#
#-------------------------------------------------------------------------------

import os
import sys
import ldap
import time
import getopt
import logging

from datetime import datetime

#-------------------------------------------------------------------------------

from RTE import dcl

#-------------------------------------------------------------------------------

__version__   = "1.0.0"
__id__        = "@(#)  search.py  [%s]  01/05/2008"

verbose_flg   = False

debug_level   = 0

table_name    = "people"
DSERVER_PORT  = 9570
MAX_REQUESTS  = 200

lf            = None
log           = None

targets       = {
                   'hx30'     : { 'host': 'hx30',     'port' : 6389, 'type' : 'OpenLDAP' },
                   'hx77'     : { 'host': 'hx77',     'port' : 2389, 'type' : 'OpenLDAP' },
                   'hx463'    : { 'host': 'hx463',    'port' : 2389, 'type' : 'OracleOID' },
                   'hx463b'   : { 'host': 'hx463',    'port' : 6389, 'type' : 'OracleOID' },
                   'hx664'    : { 'host': 'hx664',    'port' : 2389, 'type' : 'OracleOID' },
                   'hx665'    : { 'host': 'hx665',    'port' : 2389, 'type' : 'OracleOID' },
                   'dev'      : { 'host': 'ldap-dev', 'port' : 2389, 'type' : 'OracleOID' },
                   'prod'     : { 'host': 'openldap', 'port' : 2389, 'type' : 'OpenLDAP' },
                }

target        = 'hx664'
ldap_host     = 'hx664'
ldap_port     = 2389
ldap_type     = 'OracleOID'

#===============================================================================

def INFO(msg):
   if log: log.info(' ' + msg)
   if verbose_flg: print "[test]  %s" % msg

#-------------------------------------------------------------------------------

def ERROR(msg):
   if log: log.error(msg)
   sys.stderr.write('[test]  %s\n' % msg)

#-------------------------------------------------------------------------------

def WARNING(msg):
   if log: log.warning('*****' + msg + '*****')
   if verbose_flg: print "[test]  %s" % msg

#===============================================================================

def the_time():
   t = float(ref_time(False)) * 0.001

   return t

#------------------------------------------------------------------------------

t_reference = None

def ref_time(flg):
   global t_reference

   t_now  = datetime.now()

   if (flg):
      t_reference   = t_now
      t             = 0
   else:
      t_delta       = t_now - t_reference
      t             = ((t_delta.seconds * 1000000) + t_delta.microseconds)/1000.0

   return t

#===============================================================================

def query(no_queries):
   ds = dcl.dcl(port=DSERVER_PORT)

   if (ds == None):
      print("Connection to data server failed - is data server process running?\n")
      return 1

   type_ref  = ds.RegisterType(table_name)

   if debug_level > 0:print "Data type \"%s\" registered as %d" % (table_name,  type_ref)

   cnt = 0

   l = ldap.initialize("ldap://%s:%d" % (ldap_host, ldap_port))

   l.simple_bind_s("","")

   if ldap_type == 'OpenLDAP':
      base_dn = "ou=groups,dc=auspost,dc=com"
   else:
      base_dn = "cn=Users,ou=prodsupp,dc=auspost,dc=com,dc=au"

   print "BaseDN = %s" % base_dn

   while cnt < no_queries:
      cnt += 1

      sp  = ds.GetNext(type_ref)

      if sp != None:
         uid   = sp[0]
         group = sp[1]
         desc  = sp[2]
      else:
         print "Type %d exhausted" % (pid, type_ref)
         return

      ref_time(True)

      # rows = l.search_s(dn, ldap.SCOPE_SUBTREE, "(&(objectclass=auspostuser)(uid=a*))")
      # filter = "(objectclass=*)"
      filter = "(&(objectclass=auspostuser)(uid=%s*))" % uid
      rows = l.search_s(base_dn, ldap.SCOPE_SUBTREE, filter)

      t_query = the_time()

      row_cnt = len(rows)

      # for row in rows:
         # row_cnt +=  1

         # col0 = row[0].split(', ')[0]

         # uid  = col0.split(',')[0].split('=')[1]
         # type = col0.split(',')[1].split('=')[1]

         # if row[1].has_key('groups'):
            # group = row[1]['groups'][0].split(',')[0].split('=')[1]
         # else:
            # group = ''

         # print "%s,%s,%s" % (uid, type, group)


      msg = "%03d uid %-35s  [%.3f] sec  %3d rows returned" % (cnt, uid, t_query, row_cnt)

      sys.stderr.write("%s\n" % msg)
      sys.stderr.flush()

      INFO(msg)
      # lf.write("%s\n" % msg)
      # lf.flush()

#-------------------------------------------------------------------------------

def init():
   global lf
   global log

   pid      = os.getpid()

   if debug_level > 0:  print "My PID is %d" % pid

   log  = logging.getLogger('search')
   hdlr = logging.FileHandler('log/%s.log' % ldap_host)
   fmtr = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

   hdlr.setFormatter(fmtr)
   log.addHandler(hdlr) 
   log.setLevel(logging.INFO)

   INFO("===== Started processing ==================================================")

   cnt = 0

#===============================================================================

def main():
   global verbose_flg
   global debug_level
   global MAX_REQUESTS
   global ldap_host
   global ldap_port
   global ldap_type
   global target

   try:
      opts, args = getopt.getopt(sys.argv[1:], "c:dD:M:t:vVw?")
   except getopt.error, msg:
      print __doc__
      return 1

   for o, a in opts:
      if o == '-?':
         print __doc__
         return 1
      elif o == '-c':
         connector_no   = int(a)
      elif o == '-d':
         debug_level   += 1
      elif o == '-D':
         debug_level    = int(a)
      elif o == '-M':
         MAX_REQUESTS    = int(a)
      elif o == '-t':
         target          = a
      elif o == '-v':
         verbose_flg    = True
      elif o == '-V':
         print "[search_dev]  Version: %s" % __version__
         return 1
      else:
         print __doc__
         return 1

   sys.stderr.write("[test]  Working directory is %s\n" % os.getcwd())
   sys.stderr.flush()

   if (debug_level > 0): print "Debugging level set to %d" % debug_level

   if args:
      for arg in args:
         print arg

   ldap_host     = targets[target]['host']
   ldap_port     = targets[target]['port']
   ldap_type     = targets[target]['type']

   init()

   query(MAX_REQUESTS)

   return 0

#-------------------------------------------------------------------------------

if __name__ == '__main__' or __name__ == sys.argv[0]:
   try:
      sys.exit(main())
   except KeyboardInterrupt, e:
      print "[search_dev]  Interrupted!"

#-------------------------------------------------------------------------------

"""
Revision History:

     Date     Who   Description
   --------   ---   ------------------------------------------------------------
   20080501   plh   Initial implementation

Problems to fix:

To Do:

Issues:

"""

DataServer with data to enable this script to be used... DataServer archice

LoadRunner Implementation

vuser_init.c

vuser_init()
{
   lr_start_transaction("mldap_logon");

   mldap_logon("Login",
		"URL=ldap://hx30:6389",
		LAST);

   lr_end_transaction("mldap_logon", LR_AUTO);

   return 0;
}  // vuser_init

Action.c

Action()
{
    lr_start_transaction("LDAP_Search_UID");

	mldap_search("LDAP Search", 
               "Base=OU=people,DC=auspost,DC=com", 
               "Scope=Subtree", 
               "Filter=(&(objectclass=auspostuser)(uid={UID}))", 
               "Timeout=10", 
               "Mode=SYNC", 
               LAST); 

	lr_end_transaction("LDAP_Search_UID", LR_AUTO);

	lr_message(">>>>> UID %s", lr_eval_string("{UID}"));

	return 0;
}  // Action

vuser_end.c

vuser_end()
{
   lr_start_transaction("mldap_logoff");

   mldap_logoff();

   lr_end_transaction("mldap_logoff", LR_AUTO);

   return 0;
}  // vuser_end