Difference between revisions of "LDAP Search Script"

From PeformIQ Upgrade
Jump to navigation Jump to search
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Python Implementation=
=Python Implementation=


This script draws the required Manifest Ids from the [[data server]] which is described elsewhere.
This script draws the required search patterns (UID) from the [[Data Server]] (AKA [[dserver]]) which is described elsewhere.


<pre>
<pre>
Line 24: Line 24:


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


verbose_flg  = False
verbose_flg  = False


debug_level  = 0
debug_level  = 0


table_name    = "people"
table_name    = "people"
Line 38: Line 39:


targets      = {
targets      = {
                   'hx30'     : { 'host': 'hx30',     'port' : 6389, 'type' : 'OpenLDAP' },
                   'oracle'       : { 'host': 'xxx', 'port' : nnn, 'type' : 'OracleOID' },
                  'hx77'    : { 'host': 'hx77',    'port' : 2389, 'type' : 'OpenLDAP' },
                   'openldap'      : { 'host': 'xxx', 'port' : nnn, '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'
target        = 'test'
ldap_host    = 'hx664'
ldap_host    = 'test'
ldap_port    = 2389
ldap_port    = 389
ldap_type    = 'OracleOID'
ldap_type    = 'OracleOID'


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


#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
Line 63: Line 58:
def ERROR(msg):
def ERROR(msg):
   if log: log.error(msg)
   if log: log.error(msg)
   sys.stderr.write('[test]  %s\n' % msg)
   sys.stderr.write('[ldap_search]  %s\n' % msg)


#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
Line 69: Line 64:
def WARNING(msg):
def WARNING(msg):
   if log: log.warning('*****' + msg + '*****')
   if log: log.warning('*****' + msg + '*****')
   if verbose_flg: print "[test]  %s" % msg
   if verbose_flg: print "[ldap_search]  %s" % msg


#===============================================================================
#===============================================================================
Line 116: Line 111:


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


   print "BaseDN = %s" % base_dn
   print "[ldap_search]  BaseDN = %s" % base_dn


   while cnt < no_queries:
   while cnt < no_queries:
Line 132: Line 127:
         desc  = sp[2]
         desc  = sp[2]
       else:
       else:
         print "Type %d exhausted" % (pid, type_ref)
         print "[ldap_search]  Type %d exhausted" % (pid, type_ref)
         return
         return


       ref_time(True)
       ref_time(True)


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


Line 159: Line 154:
             # group = ''
             # group = ''


         # print "%s,%s,%s" % (uid, type, group)
         # print "[ldap_search]  %s,%s,%s" % (uid, type, group)




Line 179: Line 174:
   pid      = os.getpid()
   pid      = os.getpid()


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


   log  = logging.getLogger('search')
   log  = logging.getLogger('ldap_search')
   hdlr = logging.FileHandler('log/%s.log' % ldap_host)
   hdlr = logging.FileHandler('log/%s.log' % ldap_host)
   fmtr = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
   fmtr = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
Line 227: Line 222:
         verbose_flg    = True
         verbose_flg    = True
       elif o == '-V':
       elif o == '-V':
         print "[search_dev]  Version: %s" % __version__
         print "[ldap_search]  Version: %s" % __version__
         return 1
         return 1
       else:
       else:
Line 233: Line 228:
         return 1
         return 1


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


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


   ldap_host    = targets[target]['host']
   ldap_host    = targets[target]['host']
Line 258: Line 249:
       sys.exit(main())
       sys.exit(main())
   except KeyboardInterrupt, e:
   except KeyboardInterrupt, e:
       print "[search_dev]  Interrupted!"
       print "[ldap_search]  Interrupted!"


#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
Line 267: Line 258:
     Date    Who  Description
     Date    Who  Description
   --------  ---  ------------------------------------------------------------
   --------  ---  ------------------------------------------------------------
   20080501   plh  Initial implementation
   20031014   plh  Initial implementation


Problems to fix:
Problems to fix:
Line 278: 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=


Line 305: Line 295:


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

Latest revision as of 10: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