Release of grains plugin to racktables-contribs
[racktables-contribs] / ad-import-to-racktables.php
1 #!/usr/bin/php -q
2 <?php
3 // Path to racktables secret.php file with db credentials
4 require "/var/www/html/inc/secret.php";
5
6 $racktables_perms = "# NOTE: Do not edit this file since it is created automatically by a cron job every night\n\n";
7
8 $ds=ldap_connect("ad.yourcompany.com");
9
10 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
11 ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
12
13 // Create this normal Domain User first to be able to read from AD
14 $ldapbind = ldap_bind($ds, "ServiceAccount", "ThePasswordHere");
15
16 if (!$ldapbind) {
17 echo "LDAP bind failed...";
18 }
19
20 // START
21 $group = "MyAdminGroup";
22 $racktables_perms .= "# Users imported from Active Directory group $group at " . date("Y-m-d H:i:s") . "\n\n";
23 $dn = "DC=ad,DC=yourcompany,DC=com";
24 $filter="(|(cn=$group))";
25 $props = array("member");
26
27 $sr=ldap_search($ds, $dn, $filter, $props);
28
29 $entry = ldap_first_entry($ds, $sr);
30 $attrs = ldap_get_attributes($ds, $entry);
31 $values = ldap_get_values($ds, $entry,"member");
32
33 for ($i=0; $i < $values["count"]; $i++)
34 {
35
36 $filter = "(objectclass=*)";
37
38 $props = array("sAMAccountName");
39 $sr=ldap_read($ds, $values[$i], $filter, $props);
40
41 $entry = ldap_get_entries($ds, $sr);
42 $user = strtolower($entry[0]["samaccountname"][0]);
43
44 $racktables_perms .= "allow {\$username_$user}\n";
45 }
46
47 $racktables_perms .= "\n";
48
49 //END
50 //ADD ANOTHER GROUP IMPORT HERE IF NEEDED
51
52 ldap_close($ds);
53
54 $racktables_perms .= "\n";
55 $racktables_perms .= "# Admin and Default (read-only)\n";
56 $racktables_perms .= "allow {\$userid_1} or {\$tab_default}\n";
57
58 //Now update the database
59
60 try {
61 $dbh = new PDO($pdo_dsn, $db_username, $db_password);
62
63 $count = $dbh->exec("UPDATE Script SET script_text = '$racktables_perms' WHERE script_name = 'RackCode'");
64
65 if ($count != 1) {
66 echo "Warning: No records affected by UPDATE statement!";
67 }
68
69 $dbh->exec ('UPDATE Script SET script_text = NULL WHERE script_name = "RackCodeCache"');
70 $dbh = null;
71 }
72 catch(PDOException $e)
73 {
74 echo $e->getMessage();
75 }
76
77 ?>