Thursday, January 14, 2010

PHP scripts for LDAP modifications

[root@nabeelmoidu html]# cat ldap-search.php

 
// Open file handles for input and output file
$ip_handle = fopen('input.csv', 'r');
$op_handle = fopen('output.ldif','w');

$server="xx.xx.xx.xx";//Enter DC ip here
$basedn="DC=domain,DC=tld";

//User to bind to the active directory to search for the users, can be any ordinary user
$bindname="CN=binder,OU=Users,DC=domain,DC=tld";

// Read from csv, with the comma , as the delimiter
while (($rawname = fgetcsv($ip_handle, 1000, ",")) !== FALSE)
{
$searchname=$rawname[1]; // First column is the useraccount
$extension=$rawname[2]; // Second column is the extension number


$filter="sAMAccountName=".$searchname; // search filter set as per the first column

// Attempt to connect to the LDAP server
if (!($connect = ldap_connect($server))) { die ("Could not connect to LDAP server"); }
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);

// Test if the user can be bound to the LDAP
if (!($bind = ldap_bind($connect, $bindname, "passwd"))) { die ("Could not bind to $bindname"); }

// Search for the user
$result = ldap_search($connect, $basedn,$filter);


if ($result) {
$info = ldap_get_entries($connect, $result);
for ($i=0; $i<$info["count"]; $i++)
{
// Retrieve user information from the result
$userdn = $info[$i]["dn"];
$usersamname = $info[$i]["samaccountname"][0];
$usertelno = $info[$i]["telephonenumber"][0];
$useript = $info[$i]["ipphone"][0];

// Echo output to screen and to file. If phone number exists, set changetype to modify, else to add
if ($usertelno) {
echo "
dn: ".$userdn."
changetype: modify
replace: telephonenumber
telephonenumber: ".$extension."
-
";
fwrite($op_handle, "\ndn: ".$userdn."\nchangetype: modify\nreplace: telephonenumber\ntelephonenumber: ".$extension."\n-\n");
}
else {
echo "
dn: ".$userdn."
changetype: modify
add: telephonenumber
telephonenumber: ".$extension."
-
";
fwrite($op_handle, "\ndn: ".$userdn."\nchangetype: modify\nadd: telephonenumber\ntelephonenumber: ".$extension."\n-\n");
}

if ($useript) {
echo "replace: ipPhone
ipPhone: ".$extension ;
fwrite($op_handle, "replace: ipPhone\nipPhone: ".$extension."\n" );
}
else {
fwrite($op_handle, "add: ipPhone\nipPhone: ".$extension."\n" );
echo "add: ipPhone
ipPhone: ".$extension ;
}
}
echo "
";
}
else {}
ldap_unbind($connect);
}
fclose($op_handle);
fclose($ip_handle);

// Output will be

//dn: CN=Name1,OU=Department,OU=Users,DC=domain,DC=tld
//changetype: modify
//replace: telephonenumber
//telephonenumber: 5266222
//-
//replace: ipPhone
//ipPhone: 5266222
?>


The output file created by this script is then passed to ldapmodify to do the modifications
[root@nabeelmoidu html]# ldapmodify -a -v -h dc.domain.tld -D "CN=Administrator,CN=Users,DC=domain,DC=tld" -W -f /var/www/html/output.ldif

No comments: