Difference between revisions of "LDAP Search Script"

From PeformIQ Upgrade
Jump to navigation Jump to search
 
Line 269: Line 269:
</pre>
</pre>


DataServer with data to enable this script to be used... [http://www.performiq.com.au/kb/images/xxx.tz DataServer archive]
=LoadRunner Implementation=
=LoadRunner Implementation=



Latest revision as of 11:57, 2 April 2009

Python Implementation

This script draws the required search patterns (UID) from the Data Server (AKA dserver) which is described elsewhere.

#!/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__        = "@(#)  ldap_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       = {
                   'oracle'        : { 'host': 'xxx', 'port' : nnn, 'type' : 'OracleOID' },
                   'openldap'      : { 'host': 'xxx', 'port' : nnn, 'type' : 'OpenLDAP' },
                }

target        = 'test'
ldap_host     = 'test'
ldap_port     =  389
ldap_type     = 'OracleOID'

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

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

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

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

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

def WARNING(msg):
   if log: log.warning('*****' + msg + '*****')
   if verbose_flg: print "[ldap_search]  %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=xxx,dc=performiq,dc=com,dc=au"
   else:
      base_dn = "cn=xxx,ou=xxx,dc=perform,dc=com,dc=au"

   print "[ldap_search]  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 "[ldap_search]  Type %d exhausted" % (pid, type_ref)
         return

      ref_time(True)

      # rows = l.search_s(dn, ldap.SCOPE_SUBTREE, "(&(objectclass=xxx)(uid=a*))")
      # filter = "(objectclass=*)"
      filter = "(&(objectclass=xxx)(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 "[ldap_search]  %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 "[ldap_search]  My PID is %d" % pid

   log  = logging.getLogger('ldap_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 "[ldap_search]  Version: %s" % __version__
         return 1
      else:
         print __doc__
         return 1

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

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

   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 "[ldap_search]  Interrupted!"

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

"""
Revision History:

     Date     Who   Description
   --------   ---   ------------------------------------------------------------
   20031014   plh   Initial implementation

Problems to fix:

To Do:

Issues:

"""

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=xxx,DC=performiq,DC=com,DC=au", 
               "Scope=Subtree", 
               "Filter=(&(objectclass=xxx)(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