[Evolvis-commits] r18: added ldap-scripts↵

sfromm at evolvis.org sfromm at evolvis.org
Thu May 8 10:15:28 CEST 2008


Author: sfromm
Date: 2008-05-08 08:15:28 +0000 (Thu, 08 May 2008)
New Revision: 18

Added:
   trunk/gforge_base/login_management/ldap/ldap2ldap.php
   trunk/gforge_base/login_management/ldap/ldap2sql.php
   trunk/gforge_base/login_management/ldap/ldap_delete.php
Log:
added ldap-scripts


Added: trunk/gforge_base/login_management/ldap/ldap2ldap.php
===================================================================
--- trunk/gforge_base/login_management/ldap/ldap2ldap.php	                        (rev 0)
+++ trunk/gforge_base/login_management/ldap/ldap2ldap.php	2008-05-08 08:15:28 UTC (rev 18)
@@ -0,0 +1,167 @@
+#!/usr/bin/php
+<?php
+/* Christian Preilowski (c.preilowski at tarent.de)
+ *	
+ * Script to copy users with predefined attributs from a source LDAP 
+ * to a dest-LDAP
+ *
+ * 01.04.2008
+ *
+*/
+
+
+//############ SETTINGS #############
+
+//settings for evolvis-ldap at localhost
+$dest_ldaphost = "localhost";
+$dest_dn = "dc=my, dc=path, dc=de";
+$dest_ldapuser="admin";
+$dest_ldappw="mypassword";
+
+$dest_bind_rdn= "cn=".$dest_ldapuser.", ".$dest_dn;
+$dest_addr="ou=People, ".$dest_dn;
+$dest_filter = "objectClass=person";
+
+$src_ldaphost = "path.to.ldap";
+$src_dn = "dc=my dc=path, dc=de";
+$src_ldapuser="user";
+$src_ldappw="mypassword";
+
+
+$src_bind_rdn= "uid=".$src_ldapuser.",cn=users, ".$src_dn ;
+$src_filter = "objectClass=organizationalPerson";
+$src_addr="cn=users, ".$src_dn;
+
+
+//############ CONNECT #############
+
+echo ">> CONNECTING TO: ".$dest_ldaphost."\n";
+$dest_ds=ldap_connect($dest_ldaphost);
+echo ">> CONNECTING TO: ".$src_ldaphost."\n\n";
+$src_ds=ldap_connect($src_ldaphost);
+
+if (!$src_ds) {
+    error_log ("ERROR: Unable to connect to source LDAP server. Exiting.",0);
+    exit;
+}
+
+if (!$dest_ds) {
+    error_log ("ERROR: Unable to connect to destination LDAP server. Exiting.",0);
+    exit;
+}
+
+//########### BIND #################
+//bind with password, necessary to get userPasswords
+echo ">> BINDING \n\n";
+ldap_set_option($src_ds, LDAP_OPT_PROTOCOL_VERSION, 3); //otherwise "protocol error"
+ldap_set_option($dest_ds, LDAP_OPT_PROTOCOL_VERSION, 3);
+
+$src_lb = ldap_bind($src_ds, $src_bind_rdn, $src_ldappw);
+$dest_lb = ldap_bind($dest_ds, $dest_bind_rdn, $dest_ldappw);
+
+if (!$src_lb) {
+    error_log ("ERROR: Unable to bind to source LDAP server with \"".$src_bind_rdn."\". Exiting.",0);
+    exit;
+}
+if (!$dest_lb) {
+    error_log ("ERROR: Unable to bind to destination LDAP server with \"".$dest_bind_rdn."\". Exiting.",0);
+    exit;
+}
+
+//################ SEARCH & INSERT ###########
+
+echo ">> SEARCHING IN: ".$src_ldaphost." DN:".$src_addr."\n";
+$src_sr=ldap_search($src_ds, $src_addr, $src_filter);
+echo ">> SEARCHING IN: ".$dest_ldaphost." DN:".$dest_addr."\n\n";
+$dest_sr=ldap_search($dest_ds, $dest_addr, $dest_filter);
+
+//get dest entries an save the UIDs in an array
+$dest_entries = ldap_get_entries($dest_ds, $dest_sr);
+$dest_entries_array = array();
+for ($i=0; $i<sizeof($dest_entries); $i++) {
+	$dest_entries_array[$i] = $dest_entries[$i]["uid"][0];
+}
+
+//get src entries
+$info = ldap_get_entries($src_ds, $src_sr);
+echo ">>CECKING FOR NEW OR MODIFIED USERS:\n";
+//create an array for the UIDs of all inserted items
+$inserted_items = array();
+$modified_items = array();
+$inserted_item_count = 0;
+$modified_item_count = 0;
+//------------------- loop through LDAP user records -----------------------
+for ($i=0; $i<$info["count"]; $i++) {
+
+//	$notice_criteria = $info[$i]["givenname"];
+
+	if ($notice_criteria){
+
+	    //LDAP labels have to be lower case!
+	    $uname = $info[$i]["uid"][0];
+	
+	    // prepare new item
+	    $item["uid"] = $uname;
+		$item["userpassword"] = $info[$i]["userpassword"][0];
+		echo "USERPASSWD: ".$item["userpassword"]."\n";
+	    $item["givenname"] = $info[$i]["givenname"][0];
+	    $item["cn"] = $info[$i]["cn"][0];
+	    $item["sn"] = $info[$i]["sn"][0];
+	    $item["mail"] = $info[$i]["mailprimaryaddress"][0];
+	    $item["loginshell"] = "/lib/anonsvnsh";
+		//TODO generate uid and gid  
+	    $item["uidnumber"] = 0;
+	    $item["gidnumber"] = 0;
+	    $item["homeDirectory"] = "/var/lib/gforge/chroot/home/users/".$uname;
+
+	    $item["objectclass"][0]='inetOrgPerson';
+	    $item["objectclass"][1]='organizationalPerson';
+	   	$item["objectclass"][2]='person';
+	    $item["objectclass"][3]='posixAccount';
+	    $item["objectclass"][4]='top';
+	    $item["objectclass"][5]='shadowAccount';
+	    $item["objectclass"][6]='debGforgeAccount';
+	
+		//search in dest_entries_array if entry already exists
+		if (array_search  ($uname , $dest_entries_array)){
+			//the item already exixts!
+		
+			// modify item 
+			$r = ldap_modify($dest_ds, "uid=".$uname.",".$dest_addr, $item);
+			echo " * modifing: ".$uname.($r ? " (success) " : " (failed) ")."\n";
+
+		    if ($r){
+	            $modified_item_count++;
+	
+	            //add UID to inserted_items array
+	            $modified_items[$i] = $uname;
+	        }
+	
+		}else{
+			// insert item into dest-LDAP
+			$r = ldap_add($dest_ds, "uid=".$uname.",".$dest_addr, $item);
+			echo " * inserting: ".$uname.($r ? " (success) " : " (failed) ")."\n";
+	
+			if ($r){
+				$inserted_item_count++;
+	
+				//add UID to inserted_items array
+				$inserted_items[$i] = $uname;
+			}
+		}
+
+	}else{
+		echo " * ignoreing: ".$info[$i]["uid"][0]."\n";
+	}
+}//end for loop through LDAP records
+
+echo "\nNumber of LDAP records: ". $info["count"] ."\n";
+echo "Number of inserted records: ".$inserted_item_count++."\n";
+echo "Number of modified records: ".$modified_item_count++."\n";
+
+//############ CLOSE ###############
+
+ldap_close($src_ds);
+ldap_close($dest_ds);
+
+?>


Property changes on: trunk/gforge_base/login_management/ldap/ldap2ldap.php
___________________________________________________________________
Name: svn:executable
   + *

Added: trunk/gforge_base/login_management/ldap/ldap2sql.php
===================================================================
--- trunk/gforge_base/login_management/ldap/ldap2sql.php	                        (rev 0)
+++ trunk/gforge_base/login_management/ldap/ldap2sql.php	2008-05-08 08:15:28 UTC (rev 18)
@@ -0,0 +1,315 @@
+#!/usr/bin/php
+<?php
+/* CREATED JH 25.02.08
+ * based on example in http://de.php.net/ldap
+ *
+ * CHANGED 06.03.08 JH for evolvis user attributes mail, sn, givenName
+ * CHANGED 12.03.08 JH parameters on command line
+ * CHANGED 12.03.08 JH insert, delete
+ * CHANGED 12.03.08 JH check for password length in case of change or insert
+*/ 
+
+//global vars and functions for database connection and authentication
+//we use methods from User.class only sparsely as they depend mainly on web I/O
+require ('/etc/gforge/local.inc');
+require ('/usr/share/gforge/common/include/database.php');
+require ('/usr/share/gforge/common/include/account.php');
+require ('/usr/share/gforge/common/include/Error.class');   //needed by User.class
+require ('/usr/share/gforge/common/include/User.class');    //for $u->delete()
+
+error_log ("ldap2sql notice: Starting....... ",0);
+
+$username = false;
+$filter = "objectClass=person"; //specify filter for ldap_search
+
+//set themeid
+if (! $sys_default_theme_id )
+	$sys_default_theme_id=22;
+
+//argument defaults
+$ldaphost = "localhost";
+$dn = "dc=my, dc=domain, dc=de";
+$ldapuser="SF_robot";
+$ldappw="mypassword";
+$deactivate = false;
+
+
+//------------------- get arguments from command line -----------------------
+$error_param = "ldap2sql error: Unrecognized option.\nUsage: \n-h hostname (default: localhost)\n-u username (default: not specified, all users)\n-dn \"distinguished name\" (default: \"dc=evolvis, dc=org\")\n-lu ldapuser (with permission to read passwords, default: SF_robot)\n-lp \"ldapuserpassword\"\n-d yes/no (deactivate deprecated users? default: no)";
+
+$logstring ="";
+
+if ($argc > 1){
+    //loop only until last-but-one
+    for ($i=1; $i<$argc; $i++) {
+        if (strpos($argv[$i], '-') === 0) {
+            //is there a value to the key? if not, exit
+            if (!isset($argv[$i+1]) || strpos($argv[$i+1], '-') === 0){
+                error_log ($error_param,0);
+                exit;            
+            }
+            $key = str_replace('-', '', $argv[$i]);
+            switch ($key){
+            case "h":
+                $ldaphost=$argv[$i+1];
+                $logstring .= " hostname=".$ldaphost;
+                break;
+            case "u":
+                $username=$argv[$i+1];
+                $filter = "uid=".$username;
+                $logstring .= " username=".$username;
+                break;
+            case "dn":
+                $dn = $argv[$i+1];
+                $logstring .= " dn=\"".$dn."\"";
+                break;
+            case "lu":
+                $ldapuser = $argv[$i+1];
+                $logstring .= " lu=".$ldapuser;
+                break;
+            case "lp":
+                //note: quotation marks get stripped automatically
+                $ldappw =  $argv[$i+1];
+                $logstring .= " lp=\"".$ldappw."\"";
+                break;
+            case "d":
+                $deactivate =  $argv[$i+1];
+                $logstring .= " d=".$deactivate;
+                break;                                
+            default: 
+                error_log ($error_param,0);
+                exit;
+            }//end switch
+        }//end if
+    }//end for
+    error_log ("ldap2sql notice: Recognized parameters:".$logstring,0);
+}
+
+
+//------------------- get stuff from LDAP directory -----------------------
+//connect
+$ds=ldap_connect($ldaphost); 
+if (!$ds) {
+    error_log ("ldap2sql error: Unable to connect to LDAP server. Exiting.",0);
+    exit;
+} 
+
+//bind with password, necessary to get userPasswords
+$bind_rdn= "cn=".$ldapuser.", ".$dn;
+ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); //otherwise "protocol error"
+$lb = ldap_bind($ds, $bind_rdn, $ldappw);
+if (!$lb) {
+    error_log ("ldap2sql error: Unable to bind to LDAP server with \"".$bind_rdn."\". Exiting.",0);
+    exit;
+}
+
+//search
+$sr=ldap_search($ds, "ou=People, ".$dn, $filter);  
+
+error_log ("ldap2sql notice: LDAP entries found: ". ldap_count_entries($ds, $sr),0);
+
+$info = ldap_get_entries($ds, $sr);
+
+//initialize variables
+$id_arr = array();
+
+$cntnew = 0; //in LDAP, not in DB
+$cntins = 0; //records inserted in DB
+$cntupd = 0; //records updated in DB
+$cntold = 0; //in DB, not in LDAP
+$cntdel = 0; //records deleted from DB
+
+//database connect
+db_connect();
+
+//------------------- loop through LDAP user records -----------------------
+for ($i=0; $i<$info["count"]; $i++) {
+    //we always only take the first item of the value array 
+    //LDAP labels have to be lower case!
+    //we use the following two several times, so we shorten them
+    $pw = $info[$i]["userpassword"][0];
+    $uname = $info[$i]["uid"][0];
+    
+    //construct array of all usernames in LDAP directory (necessary for deletion, see below)
+    $id_array[] = $uname;
+    
+    //check for password length and if username is valid in Gforge
+    //checks modeled after account.php
+    if (strlen($pw) < 6) {
+        error_log ("ldap2sql error: Invalid password (".$pw.") for user ".$uname. ": Password has to have at least 6 characters in GForge",0);
+        break;
+    }
+    if (strlen($uname) < 3 || strlen($uname) > 15 || 
+        strrpos($uname,' ') > 0 || !ereg('^[a-z][-a-z0-9_]+$', $uname)){
+        error_log ("ldap2sql error: Username ".$uname." not valid in GForge. Has to have 3 - 15 characters, no space, only letters, digits, \"-\" and \"_\", has to start with a letter.",0);
+        break;
+    }        
+    //------------------ check record before doing sth ------------------------
+    
+    $sql_select = "SELECT firstname, lastname, realname, shell, unix_uid, unix_gid, ".
+                    "unix_pw, user_pw, email, status, sys_state ".
+                    "FROM users WHERE user_name='".$uname."'";
+    $res_sel = db_query($sql_select);
+    
+    if (!$res_sel) {
+        error_log ("ldap2sql error: ".$sql_select." - ". db_error(),0);
+        break;
+    }
+    elseif (db_numrows($res_sel)<1) {
+        //---------------------- INSERT new record --------------------------
+        error_log ("ldap2sql notice: No DB record found with user_name=".$uname.".  Will be inserted.",0);
+        $cntnew ++;
+        db_free_result($res_sel);
+       
+	//    echo "\nPASSWORD: ".$pw."\n PASSWORD(md5): ".md5($pw)."\n PASSWORD(genunix): ".account_genunixpw($pw)."\n";
+
+        //See User.class: create() function. See users-table for defaults, e.g. status='A'
+        $sql_insert = "INSERT into users ".
+                        "(user_name, user_pw, unix_pw, firstname, lastname, realname, ".
+                        "shell, unix_uid, unix_gid, email, ". 
+                        "add_date, theme_id) ".
+                        "VALUES ('".$uname."', '".
+                                    md5($pw)."', '".
+                                    account_genunixpw($pw)."', '".
+                                    $info[$i]["givenname"][0]."', '".
+                                    $info[$i]["sn"][0]."', '".
+                                    $info[$i]["cn"][0]."', '".
+                                    $info[$i]["loginshell"][0]."', '".
+                                    $info[$i]["uidnumber"][0]."', '".
+                                    $info[$i]["gidnumber"][0]."', '".
+                                    $info[$i]["mail"][0]."', '".
+                                    time()."', '".
+                                    $sys_default_theme_id."') ";
+        //begin transaction
+        db_begin();        
+        $res_ins=db_query($sql_insert);
+
+        if (!$res_ins) {
+            error_log ("ldap2sql error: Could not insert user.".db_error().$sql_insert,0);
+            db_rollback();
+            break;
+        } else {
+            db_commit();
+            $cntins++;
+            error_log ("ldap2sql notice: User ".$uname." inserted.",0);
+            db_free_result($res_ins);
+        }
+    }
+    else {
+        //------------ UPDATE record (only if different) -------------        
+        $record = db_fetch_array($res_sel);
+        //compare passwords - normal users: clear, admin user: crypt
+        $pw_eq = true;
+        if (strpos($pw,"{crypt}") === 0 && $record['sys_state']!="N"){
+            $pw_eq = ("{crypt}".$record['unix_pw'] == $pw);
+            $pw_db = str_replace('{crypt}', '', $pw);; //we write the crypted pw to the db
+        }
+        else {
+            $pw_eq = ($record['user_pw'] == md5($pw));
+            $pw_db = md5($pw);
+        }
+        
+        if ($record['realname']     == $info[$i]["cn"][0] &&
+            $record['firstname']    == $info[$i]["givenname"][0] &&
+            $record['lastname']     == $info[$i]["sn"][0] &&            
+            $record['shell']        == $info[$i]["loginshell"][0] &&
+            $record['unix_uid']     == $info[$i]["uidnumber"][0] &&                
+            $record['unix_gid']     == $info[$i]["gidnumber"][0] &&
+            $pw_eq &&
+            $record['status']       == 'A' && //if user is in LDAP, it has to be "active" in DB 
+            $record['email']        == $info[$i]["mail"][0]) { 
+                error_log ("ldap2sql notice: Checking user ".$uname.": No difference - record unchanged.");
+        }
+        else{
+            error_log ("ldap2sql notice: User ".$uname." before update: ".
+                $record['firstname'].", ".$record['lastname'].", ".$record['realname'].", ".
+                $record['shell'].", ".$record['unix_uid'].", ".$record['unix_gid'].", ".
+                $record['user_pw'].", ".$record['email'].", ".$record['status'],0);
+            
+            db_free_result($res_sel);
+            
+            $sql_update = "UPDATE users SET ". 
+                    "firstname='" .   $info[$i]["givenname"][0]."', ".
+                    "lastname='" .    $info[$i]["sn"][0]."', ".
+                    "realname='" .    $info[$i]["cn"][0]."', ".
+                    "shell='" .       $info[$i]["loginshell"][0]."', ".
+                    "unix_uid='" .    $info[$i]["uidnumber"][0]."', ".
+                    "unix_gid='" .    $info[$i]["gidnumber"][0]."', ".
+                    //"user_pw='" .     $pw_db."', ".
+                    "email='" .       $info[$i]["mail"][0]."', ".
+                    "status='" .      "A' ". //if user is in LDAP, forge status is "active"
+                "WHERE user_name='" . $uname."' ";
+            
+            error_log ("ldap2sql notice: ".$sql_update,0); 
+            
+            //begin transaction
+            db_begin();
+            $res_up = db_query($sql_update);
+            if (!$res_up) {
+                error_log ("ldap2sql error: Could not update user record: ".db_error());
+                db_rollback();
+            } else {
+                db_commit();
+                error_log ("ldap2sql notice: Updated.");
+                $cntupd ++;
+            }           
+
+            db_free_result($res_up);
+        }//end update
+    }//end else
+}//end for loop through LDAP records
+
+
+//---------------------- DELETE records (set inactive) ------------------
+//do we want to deactivate?
+if ($deactivate && ($deactivate == "yes" || $deactivate == "y" || $deactivate == "Y")){  
+    //was the script called with username parameter? Then filter.
+    if ($username) $filter_user = " AND user_name='".$username."'";
+    //construct WHERE-part
+    if (count($id_array)>0){
+        $where_part = " AND user_name NOT IN ('".implode("', '", $id_array)."')";
+    }
+    //get all user_ids from (not deactivated) users that are in DB but not in LDAP
+    $sql_users = "SELECT user_name FROM users ".
+                 "WHERE status!='D' AND user_name!='None' AND user_name!='admin'".
+                $filter_user.$where_part;
+    $res_users = db_query($sql_users);
+    
+    if (!$res_users) {
+        error_log ("ldap2sql error: ".$sql_users." - ". db_error(),0);
+    }
+    elseif (db_numrows($res_users)<1) {
+        error_log ("ldap2sql notice: The database is up to date, nothing to delete.",0);
+    }
+    else {
+        $cntold = db_numrows($res_users);
+        error_log ("ldap2sql notice: ".$cntold." deprecated users in the database, deactivating...",0);
+        $del_ok = false;
+        while ($row = db_fetch_array($res_users)) {
+            $un = $row['user_name'];
+            error_log ("ldap2sql notice: Deactivating user ".$un.".");        
+            $u = user_get_object_by_name ($un) ;
+            if (!$u) {
+                error_log ("ldap2sql error: Could not get user object.",0);
+                break;
+            }
+            $del_ok = $u->setStatus('D');
+            if ($del_ok) {
+                $cntdel++;
+            }
+            else error_log ("ldap2sql error: Could not deactivate user ".$un.". ".$u->getError(),0);
+    
+        }//end while
+    }//end else
+}//end if deactivate
+else {
+    error_log ("ldap2sql notice: Did not check for deprecated users as script not called with \"-d yes\"",0);
+}
+error_log ("ldap2sql notice: DB records updated: ".$cntupd.", not in DB: ".$cntnew." / inserted: ".$cntins.", not in LDAP: ".$cntold." / deactivated: ".$cntdel,0);
+
+//cleanup DB transactions
+system_cleanup();
+
+ldap_close($ds);
+
+?>


Property changes on: trunk/gforge_base/login_management/ldap/ldap2sql.php
___________________________________________________________________
Name: svn:executable
   + *

Added: trunk/gforge_base/login_management/ldap/ldap_delete.php
===================================================================
--- trunk/gforge_base/login_management/ldap/ldap_delete.php	                        (rev 0)
+++ trunk/gforge_base/login_management/ldap/ldap_delete.php	2008-05-08 08:15:28 UTC (rev 18)
@@ -0,0 +1,56 @@
+#!/usr/bin/php
+<?php
+/* Christian Preilowski c.preilowski at tarent.de
+ * This Script deletes the entries with the given UIDs from the defined ldap
+ *
+ * 01.04.2008
+ *
+*/
+
+//############ SETTINGS #############
+
+//settings for evolvis-ldap at localhost
+$dest_ldaphost = "localhost";
+$dest_dn = "dc=my, dc=domain, dc=de";
+$dest_ldapuser="admin";
+$dest_ldappw="mypassword";
+$dest_bind_rdn= "cn=".$dest_ldapuser.", ".$dest_dn;
+$dest_addr="ou=People, ".$dest_dn;
+
+//define array with UIDs to delete
+$delete_users = array("name(s)_of_user_to_delete");
+//############ CONNECT TO LDAP #############
+
+$dest_ds=ldap_connect($dest_ldaphost);
+
+if (!$dest_ds) {
+    error_log ("ERROR: Unable to connect to destination LDAP server. Exiting.",0);
+    exit;
+}
+
+//########### BIND TO LDAP #################
+
+//bind with password, necessary to get userPasswords
+ldap_set_option($dest_ds, LDAP_OPT_PROTOCOL_VERSION, 3);
+
+$dest_lb = ldap_bind($dest_ds, $dest_bind_rdn, $dest_ldappw);
+
+if (!$dest_lb) {
+    error_log ("ERROR: Unable to bind to destination LDAP server with \"".$dest_bind_rdn."\". Exiting.",0);
+    exit;
+}
+
+
+//############ DELETE ENTRIES ##############
+
+echo ">>>DELETING USER(S):\n";
+
+for ($i=0;$i<sizeof($delete_users);$i++){
+	$r = ldap_delete($dest_ds, "uid=".$delete_users[$i].",".$dest_addr );
+	echo " * ".$delete_users[$i].($r ? "(success)" : "(failed)")."\n";
+}
+
+//############ CLOSE CONNECTION###############
+ldap_close($dest_ds);
+
+?>


Property changes on: trunk/gforge_base/login_management/ldap/ldap_delete.php
___________________________________________________________________
Name: svn:executable
   + *




More information about the evolvis-commits mailing list