Return to Snippet

Revision: 32616
at September 30, 2010 10:11 by mattsn0w


Initial Code
#!/bin/env python

import subprocess, optparse

parser = optparse.OptionParser('Usage: %prog Ldap user ID')
parser.add_option('-u', '--user',     dest='uid',     type='string')
parser.add_option('-v', '--verbose',  dest='verbose', action='store_true')
parser.add_option('-m', '--manager',  dest='manager', type='string')

(options, args) = parser.parse_args()

# Assign new names to constants passed in from CLI options. 
userid  = options.uid
verbose = options.verbose


class getLdap(object):
#
# This class captures the result of an ldapsearch command query and stores as a dictionary with keys : values
#
    def __init__(self, uid):
        # take the userID as input and create referencable object in the class/
        self.uid    = uid
        # This is the ldap command to be run.
        self.cmd    = '/usr/bin/ldapsearch -LLL "(uid=%s)" -x -b \'dc=example,dc=com\' -h ldap.example.com' % (self.uid)
        # Using the subprocess module proce self.cmd and store results in self.proc object.
        self.proc = subprocess.Popen([self.cmd], shell=True, stdout=subprocess.PIPE)
        # Wait for command to execute
        self.proc.wait()
        # Store command return code.
        self.proc.returncode
        # Create object for command output
        self.search = self.proc.stdout
        # for each line in the stdout object strip the \n char.
        self.search = [line.strip('\n') for line in self.search]
        # Initialize an empty dictionary.
        self.result = dict()
        # 
        for line in self.search:
            try:
                # Assign output of line split up to ONLY the first colon (':') to key and value.
                key, value = line.split(':', 1)
                # Add entry to dictionary from key & value, stripping whitespace from beginning and ends.
                self.result[key.strip()] = value.strip() 
            except:
                pass
    # End of __init__
    def __str__(self):
        lines = list()
        for key, val in self.result.items():
            lines.append('%s:%s,' % (key, val))
        return '\n'.join(lines)
    #    
    def __repr__(self):
        return self.__str__()
#
# End of Class
#

def getUserEmpStatus(uidObject):
    if uidObject.result['AccountType'].lower() is 'useraccount':
        try:
            AccountStatus = uidObject.result['employstatus']
        except:
            pass
    if uidObject.result['AccountType'].lower() is 'roleaccount':
        AccountStatus = uidObject.result['AccountType']
    return AccountStatus


def getTermedMgr(uidObject):
    TermedIdMgr = uidObject.result['manager']
    MgrDict = dict()
    for line in TermedIdMgr.split(','):
        key, value = line.split('=')
        MgrDict[key] = value
    return MgrDict['uid']

def showAllKeys(uidObject):
    return uidObject


if userid and not verbose:
    user       = getLdap(userid)
    userStatus = getUserEmpStatus(user)
    usersMgr   = getTermedMgr(user)
    if userStatus.lower() in 'active assignment':
        print '%s : %s' % (userid, userStatus)
    if userStatus.lower() not in 'active assignment':
        print 'User %s is not in active assignment.\nManager is: %s' % (user, UsersMgr)
    if userStatus.lower() is 'roleaccount':
        print 'Account ID %s is a role account.' % userStatus 

if userid and verbose:
    user       = getLdap(userid)
    print '%s' % user

Initial URL


Initial Description


Initial Title
ldapsearch shortcut

Initial Tags


Initial Language
Python