Command line options for queries and actions
authorDan Scott <dan@coffeecode.net>
Thu, 8 Sep 2011 15:35:31 +0000 (11:35 -0400)
committerDan Scott <dscott@laurentian.ca>
Mon, 12 Nov 2012 17:57:57 +0000 (12:57 -0500)
Use the argparse module to enable override of user/password/hostname
options at the command line, as well as to enable different types of
queries (for example, via LDAP cn / sn / id / createTimestamp) and
enable particular actions (display the LDAP data and/or create new users
in Evergreen).

Much better than manually editing the script each time.

Signed-off-by: Dan Scott <dscott@laurentian.ca>
tools/patron-load/ldap_osrf_sync

index 5110a9f..c60d3f9 100644 (file)
@@ -1,5 +1,19 @@
 #!/usr/bin/env python
 
+# Copyright (C) 2011 Laurentian University
+# Dan Scott <dscott@laurentian.ca>
+#
+# 
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
 """
 Synchronize Evergreen user accounts with an LDAP directory via OpenSRF 
 
@@ -35,6 +49,8 @@ OSRF_WORK_OU = 'herb'
 import os
 import sys
 import ldap
+import datetime
+import argparse
 
 import oils.event
 import oils.utils.idl
@@ -94,13 +110,12 @@ class User:
         Map LDAP record to Evergreen expiry dates
         """
 
+        expiry_date = '%d-09-30' % (datetime.date.today().year + 1)
         # Faculty and staff get a long time
         if self.profile == 11 or self.profile == 14:
-            return '2020-09-30'
-        elif self.profile == 13 or self.profile == 12:
-            # Students get next academic year
-            return '2012-09-30'
-        return '2012-09-30'
+            expiry_date = '%d-09-30' % (datetime.date.today().year + 8)
+
+        return expiry_date
 
     def get_identity(self):
         """
@@ -191,7 +206,7 @@ def load_idl():
     # Get the fm_IDL.xml file from the server
     try:
         idl = urllib2.urlopen('%s://%s/%s' % 
-            (credentials.OSRF_HTTP, credentials.OSRF_HOST, credentials.IDL_URL)
+            (credentials.OSRF_HTTP, ARGS.eg_host, credentials.IDL_URL)
         )
         idlfile.write(idl.read())
         # rewind to the beginning of the file
@@ -310,16 +325,14 @@ def mod10_checksum(barcode):
         return 10 - rem
     return rem
 
-def find_new_ldap_users(con, attributes, create_date, auth):
+def find_ldap_users(con, ldap_filter, attributes, auth):
     """
     Retrieve personnel accounts from LDAP directory and process'em
     """
     base_dn = 'o=lul'
     search_scope = ldap.SCOPE_SUBTREE
-    ldap_filter = '(&(objectclass=lulEduPerson))'
-    ldap_filter = '(&(lulStudentLevel=*))'
-    ldap_filter = '(&(objectclass=lulEduPerson)(lulPrimaryAffiliation=*)(createTimestamp>=%s))' % create_date
 
+    print ldap_filter
     try:
         result_id = con.search(base_dn, search_scope, ldap_filter, attributes)
         while 1:
@@ -327,8 +340,10 @@ def find_new_ldap_users(con, attributes, create_date, auth):
             if result_data == []:
                 break
             else:
-                # dump_data(result_data)
-                create_evergreen_user(auth, result_data[0][1])
+                if ARGS.dump_ldap:
+                    dump_data(result_data)
+                if ARGS.create_users:
+                    create_evergreen_user(auth, result_data[0][1])
     except ldap.LDAPError, exc:
         print >> sys.stderr, exc
 
@@ -458,12 +473,12 @@ def dump_data(result_data):
     for key in result_data[0][1]:
         print(key, result_data[0][1][key])
 
-def ldap_create_by_date(create_date, auth):
+def ldap_create_by_date(auth):
     """
     Connect to LDAP directory and process users created since a given date
     """
 
-    con = ldap.initialize(credentials.LDAP_HOST)
+    con = ldap.initialize(ARGS.ldap_server)
     con.set_option(ldap.OPT_REFERRALS, 0)
 
     try:
@@ -471,8 +486,27 @@ def ldap_create_by_date(create_date, auth):
             'lulStudentLevel', 'lulPrimaryAffiliation', 'cn', 'mail',
             'givenName', 'sn', 'lulColleagueId', 'preferredLanguage'
         ]
-        con.simple_bind_s(credentials.LDAP_DN, credentials.LDAP_PW)
-        find_new_ldap_users(con, attributes, create_date, auth)
+        con.simple_bind_s(ARGS.ldap_user, ARGS.ldap_password)
+
+        if (ARGS.query_date):
+            ldap_filter = '(&%s(lulPrimaryAffiliation=*)(createTimestamp>=%s))' % (
+                '(objectclass=lulEduPerson)', ARGS.query_date
+            )
+        elif (ARGS.query_cn):
+            ldap_filter = '(&%s(cn=%s))' % (
+                '(objectclass=lulEduPerson)', ARGS.query_cn
+            )
+        elif (ARGS.query_sn):
+            ldap_filter = '(&%s(sn=%s))' % (
+                '(objectclass=lulEduPerson)', ARGS.query_sn
+            )
+        elif (ARGS.query_id):
+            ldap_filter = '(&%s(lulColleagueId=%s))' % (
+                '(objectclass=lulEduPerson)', ARGS.query_id
+            )
+        
+        find_ldap_users(con, ldap_filter, attributes, auth)
+
     except ldap.LDAPError, exc:
         print >> sys.stderr, "Could not connect: " + exc.message['info']
         if type(exc.message) == dict and exc.message.has_key('desc'):
@@ -483,19 +517,69 @@ def ldap_create_by_date(create_date, auth):
     finally:
         con.unbind()
 
+def parse_args():
+    """
+    Parse the command line options for the script
+    """
+    parser = argparse.ArgumentParser()
+    parser.add_argument('-d', '--dump-ldap', action='store_true',
+        help='Dump the LDAP results to STDOUT'
+    )
+    parser.add_argument('-c', '--create-users', action='store_true',
+        help='Create new users in Evergreen'
+    )
+    parser.add_argument('--query-cn',
+        help='Search LDAP for a specific user by cn attribute'
+    )
+    parser.add_argument('--query-sn',
+        help='Search LDAP for a specific user by sn attribute'
+    )
+    parser.add_argument('--query-id',
+        help='Search LDAP for a specific user by id attribute'
+    )
+    parser.add_argument('-date', '--query-date',
+        help='Search LDAP for users created since (YYYYMMDDHHMMSSZ)'
+    )
+    parser.add_argument('-U', '--eg-user', nargs='?',
+        help='Evergreen user name', default=credentials.OSRF_USER
+    )
+    parser.add_argument('-P', '--eg-password', nargs='?',
+        help='Evergreen password', default=credentials.OSRF_PW
+    )
+    parser.add_argument('-W', '--eg-workstation', nargs='?',
+        help='Name of the Evergreen workstation',
+        default=credentials.OSRF_WORK_OU
+    )
+    parser.add_argument('-H', '--eg-host', nargs='?',
+        help='Hostname of the Evergreen gateway', default=credentials.OSRF_HOST
+    )
+    parser.add_argument('-u', '--ldap-user', nargs='?',
+        help='LDAP user (DN)', default=credentials.LDAP_DN
+    )
+    parser.add_argument('-p', '--ldap-password', nargs='?',
+        help='LDAP password', default=credentials.LDAP_PW
+    )
+    parser.add_argument('-s', '--ldap-server', nargs='?',
+        help='LDAP server name or IP address', default=credentials.LDAP_HOST
+    )
+    args = parser.parse_args()
+    return args
+
 if __name__ == '__main__':
     import doctest
     doctest.testmod()
 
+    ARGS = parse_args()
+
     # Set the host for our requests
-    osrf.gateway.GatewayRequest.setDefaultHost(credentials.OSRF_HOST)
+    osrf.gateway.GatewayRequest.setDefaultHost(ARGS.eg_host)
 
     # Pull all of our object definitions together
     load_idl()
 
     # Log in and get an authtoken
     AUTHTOKEN = osrf_login(
-        credentials.OSRF_USER, credentials.OSRF_PW, credentials.OSRF_WORK_OU
+        ARGS.eg_user, ARGS.eg_password, ARGS.eg_workstation
     )
 
 #    UDATA = {
@@ -507,7 +591,6 @@ if __name__ == '__main__':
 #    }
 #    create_evergreen_user(AUTHTOKEN, UDATA)
 
-    # XXX Pull this in from sys.argv
-    ldap_create_by_date('20110906130000Z', AUTHTOKEN)
+    ldap_create_by_date(AUTHTOKEN)
 
 # vim: et:ts=4:sw=4:tw=78: