Itop AD Auto Import Script webservices/ad_import_accounts.php

Source: Internet
Author: User
Parameter modification:

' Simulation ', 1, $sAuthUser = Utils::readparam (' auth_user ', ' user_name ', true); $sAuthPwd = Utils::readparam (' auth_pwd ') , ' User_pass ', true);//Configuration of the Active Directory Connection ' host '     = ' 192.168.**.** ',                      //IP or FQ DN of your domain controller ' port '     = ' 389 ',                                 //LDAP port, 398=ldap, 636= LDAPS ' dn '        = ' ou=vb-user,dc=c Orp,dc=logo ',//Domain DN ' username '    = ' cn=ldapsearch,ou=special-user,ou=vb-user,dc=corp,dc=logo ',// Username with read access ' password '    = ' logo@pass ',                  //password for above



root@itsm:/var/www/html/new_itop# Vim webservices/ad_import_accounts.php
 * @author Romain Quetiez
 
  * @author Denis Flaven
  
   
 * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL *///////////////////////////////////////////////// Configuration parameters:adjust them to connect to your AD server//and configure the         Mapping between AD groups and iTop profiles$aconfig = Array (//Configuration of the Active Directory connection ' Host ' = ' 192.168.**.** ',//IP or FQDN of your domain controller ' port ' =&G T ' 389 ',//LDAP port, 398=ldap, 636= LDAPS ' dn ' = ' ou=vb-user,dc=corp,dc=  Logo ',//Domain DN ' username ' = ' cn=ldapsearch,ou=special-user,ou=vb-user,dc=corp,dc=logo ',//username with Read access ' password ' = ' logo@pass ',//password for above//Query to RET Rieve and filter the users from AD//Example:retrieve all users from the ad Group "ITop users"//' Ldap_que Ry ' = ' (& (ObjecTcategory=user (memberof=cn=itop users,cn=users,dc=combodo,dc=net)) ',//Example 2:retrieves all the Users fro  M AD ' ldap_query ' = ' (& (Objectcategory=user)) ',//Retrieve all users//which field to use        As the ITop login sAMAccountName or userPrincipalName? ' Login ' = ' sAMAccountName ',//' login ' = ' userprincipalname ',//Mapping between the AD group            S and the ITop profiles ' profiles_mapping ' = Array (//ad Group name = ITop Profile Name ' Administrators ' = ' Administrator ', ' itsm_administrator ' = ' Administrator ', ' Itsm_chang Eapprover ' = ' change approver ', ' itsm_changeimplementor ' = ' Change implementor ', ' Itsm_chang Esupervisor ' = ' Change Supervisor ', ' itsm_configurationmanager ' = ' Configuration Manager ', ' Itsm_documentauthor ' = ' Document author ', ' Itsm_portalpoweruser ' =&Gt ' Portal Power User ', ' itsm_portaluser ' = ' portal user ', ' itsm_problemmanager ' = ' problem man ' Ager ', ' itsm_servicedeskagent ' = ' service Desk Agent ', ' itsm_servicemanager ' = ' service Mana Ger ', ' itsm_supportagent ' = ' support Agent ',),//Since each ITOP user must has at Least one profile, assign the profiles//Below to users for which there is no match in the above mapping ' d  Efault_profile ' = ' Portal user ', ' default_language ' = ' ZH CN ',//default language for creating new                Users ' default_organization ' = 2,//ID of the default organization for creating new contacts );//End of configuration////////////////////////////////////////////////////////////////////////////////if (file_ Exists ('.. /approot.inc.php ') {//ITop 1.0.2 include ('.. /approot.inc.php ');} else//ITOP 1.0 & 1.0.1{define (' APPROOT ', ' ... /');} ReQuire_once (APPROOT. ' application/application.inc.php '); require_once (APPROOT. ' application/webpage.class.inc.php ') ); require_once (APPROOT. ' application/csvpage.class.inc.php '); require_once (APPROOT. ' application/ Clipage.class.inc.php '); require_once (APPROOT. ' application/startup.inc.php ');//List of attributes to retrieve$ Aattribs = Array (' sAMAccountName ', ' sn ', ' givenname ', ' userprincipalname ', ' cn ', ' memberof ', ' Mail ',       ); $g _auserscache = null;    Cache of all the ITop users to speed up searches$g_aprofilescache = null; Cache of all ITop profiles/** * Helper function to read attributes from LDAP data * @param hashes the LDAP data for one I TEM as returned by Ldap_search * @param string The name of the attribute to retrieve * @return mixed null if no such attri Bute, a scalar or a array depending on the * number of values for the attribute.       */function Readldapvalue ($aEntry, $sValueName) {if (Array_key_exists ($sValueName, $aEntry)) { $iCount = $aEntry [$sValueName] [' count '];                        Switch ($iCount) {case 0://No value, return null return null;                        Case 1://Just One value, return it return $aEntry [$sValueName][0]; Default://Many values, return all of them as an array//except the ' Count ' entry $aVal            ues = $aEntry [$sValueName];            unset ($aValues [' count ']);        return $aValues; }} return null;} /** * Helper function processes 1 user at a time * @param $aData hash of the input data from Active Directory * @param $ Index integer The index of the current user in the AD query (for reporting) * @param $aConfig hash of the configuration param Eter * @param $oChange cmdbchange change to record all the changes or NULL if simulation mode * @return string the action Undertaken ' created ', ' synchronized ', ' ERROR ' */function Processuser ($aData, $index, $aConfig, $oChange = null) {$sAction = ' error ';    $sUserLogin = $aData [' sAMAccountName '];    if (!is_array ($aData [' memberof '])) {$aADGroups = array ($aData [' memberof ']);    } else {$aADGroups = $aData [' memberof '];     } $aITopProfiles = Array ();        foreach ($aADGroups as $sGroupString) {$aMatches = array ();        $sShortGroupString = ";        if (Preg_match ('/^cn= ([^,]+)/', $sGroupString, $aMatches)) {$sShortGroupString = $aMatches [1]; }//echo "
   

Groupstring: $sGroupString = $sShortGroupString

"; if (Isset ($aConfig [' profiles_mapping '] [$sShortGroupString]) {$aITopProfiles [] = $aConfig [' Profiles_map Ping '] [$sShortGroupString]; }} if (count ($aITopProfiles) = = 0) {//each user must has at least one profile//Assign the ' de Fault_profile ' to this user $aITopProfiles [] = $aConfig [' Default_profile ']; } echo "

user#{$index}: {$aData [' CN ']}

\ n "; echo " "; foreach ($aData as $sAttrib = + $value) {echo " "; echo " \ n "; } echo " "; echo " \ n "; echo "
$sAttrib"; if (Is_array ($value)) {Echo implode ('
', $value); } else {echo htmlentities ($value);} echo "
ITop Profiles"; Echo Implode ('
', $aITopProfiles); echo "
"; $sLogin = $aData [$aConfig [' Login ']; $oITopUser = Getuserbylogin ($sLogin); if ($oITopUser = = null) {//Check if a contact needs to is created or not $oPerson = Getpersonbyemail ($a data[' Mail ']); if (Is_object ($oPerson)) {echo]

A person with the email= ' {$aData [' Mail ']} ' was found '. $oPerson->gethyperlink (). This is the used when creating the account.

"; } else if ($oPerson = = null) {echo '

A new person would be created.

"; $oPerson = new Person (); $oPerson->set (' first_name ', $aData [' givenname ']); $oPerson->set (' name ', $aData [' SN ']); $oPerson->set (' email ', $aData [' Mail ']); $oPerson->set (' org_id ', $aConfig [' default_organization ']); if ($oChange! = null) {$oPerson->dbinserttracked ($oChange); }} else {//Error! Several matches found?? throw new Exception ($oPerson); } $sAction = ' created '; echo "

User $sLogin'll be created in ITop

"; $oITopUser = new Userldap; $oITopUser->set (' login ', $sLogin); $oITopUser->set (' ContactID ', $oPerson->getkey ()); $oITopUser->set (' language ', $aConfig [' default_language ']); Update the Profiles $oLinkSet = Dbobjectset::fromscratch (' Urp_userprofile '); foreach ($aITopProfiles as $sProfile) {$oLink = new Urp_userprofile; $iProfileId = Getprofilebyname ($sProfile); if ($iProfileId! = null) {$oLink->set (' profileID ', $iProfileId); $oLinkSet->addobject ($oLink); } else {echo '

Error:the profile ' $sProfile ' does not exist in ITop, verify the Profiles_mapping configuration!

"; }} $oITopUser->set (' profile_list ', $oLinkSet); if ($oChange! = null) {$oITopUser->dbinserttracked ($oChange); }} else if (Is_object ($oITopUser)) {$sAction = ' synchronized '; echo "

User $sLogin (userldap:: ". $oITopUser->getkey ().") 'll be synchronized in ITop

"; Update the Profiles $oLinkSet = Dbobjectset::fromscratch (' Urp_userprofile '); $oITopUser->set (' login ', $sLogin); foreach ($aITopProfiles as $sProfile) {$oLink = new Urp_userprofile; $iProfileId = Getprofilebyname ($sProfile); if ($iProfileId! = null) {$oLink->set (' profileID ', $iProfileId); $oLinkSet->addobject ($oLink); } else {echo '

Error:the profile ' $sProfile ' does not exist in ITop, verify the Profiles_mapping configuration!

"; }} $oITopUser->set (' profile_list ', $oLinkSet); if ($oChange! = null) {$oITopUser->dbupdatetracked ($oChange); }} else {//Error, another kind of user already exists with the same login? echo "

Error: $oITopUser

"; } return $sAction;} /** * Search The given user (identified by it login) in the ITOP database * @param $sLogin string The login of the user * @return Mixed null = Nothing found, object = The user to synchronize, String = Error message */function getus Erbylogin ($sLogin) {global $g _auserscache; $result = null; if ($g _auserscache = = null) Inituserscache (); if (Isset ($g _auserscache[$sLogin])) {$oUser = $g _auserscache[$sLogin]; if (Get_class ($oUser)! = ' Userldap ') {$result = "A user with the same login ($sLogin) and not managed By LDAP already exists in ITop, the AD record would be ignored. ";} else {$result = $oUser; }} return $result;} /** * Initializes the cache for quickly searching ITop users * @param none * @return An integer number of users fetched from ITop */function Inituserscache () {global $g _auserscache; $sOQL = "Select User"; $oSearch = Dbobjectsearch::froMOQL ($sOQL); $oSet = new Cmdbobjectset ($oSearch); $iRet = $oSet->count (); while ($oUser = $oSet->fetch ()) {$g _auserscache[$oUser->get (' login ')] = $oUser; } return $iRet;} /** * Retrieves the ID of a profile (in ITop) base on its name * @param $sProfile string name of the @return int Eger ID of the profile, or null was not found */function getprofilebyname ($sProfileName) {global $g _aprofilescache; $iRet = null; if ($g _aprofilescache = = null) Initprofilescache (); if (Isset ($g _aprofilescache[$sProfileName])) {$iRet = $g _aprofilescache[$sProfileName]; } return $iRet;} /** * Initializes the cache of the ITop profiles * @param none * @return void */function Initprofilescache () {Global $g _aprofilescache; $sOQL = "Select Urp_profiles"; $oSearch = DBOBJECTSEARCH::FROMOQL ($sOQL); $oSet = new Cmdbobjectset ($oSearch); while ($oProfile = $oSet->fetch ()) {$g _aprofilescache[$oProfile->getname ()] =$oProfile->getkey (); }}/** * Search for a person by email address * @param $sEmail String * @return mixed person (if found) or null (not found) or string (Error) */function Getpersonbyemail ($sEmail) {static $oSearch = null;//OQL Query cache $person = null; if ($oSearch = = null) {$sOQL = ' SELECT person WHERE email =: Email '; $oSearch = DBOBJECTSEARCH::FROMOQL ($sOQL); } $oSet = new Cmdbobjectset ($oSearch, Array (), array (' email ' = + $sEmail)); Switch ($oSet->count ()) {case 0: $person = null; Break Case 1: $person = $oSet->fetch (); Break Default: $person = ' Several matches found: '. $oSet->count (). "Persons have the email address ' $sEmail '"; } return $person; }/****************************************************************************** * * Main program * ******* /IF (UTILS::ISMODECLI ()) {$sAuthUser = Utils::readparam (' auth_user ', ' user_name ', true); $SAUTHPWD = Utils::readparam (' auth_pwd ', ' User_pass ', true); if (Userrights::checkcredentials ($sAuthUser, $sAuthPwd)) {userrights::login ($sAuthUser);//Login & Set the User ' s language} else {echo "Access restricted or wrong credentials (' $sAuthUser ')"; Exit }}else{$_session[' login_mode '] = ' basic '; Require_once ('.. /application/loginwebpage.class.inc.php '); Loginwebpage::D ologin (); Check user rights and prompt if needed $sCSVData = Utils::readpostedparam (' CSVData ');} if (! Userrights::isadministrator ()) {echo '

Access is restricted to administrators

'; Exit;} By default, the run in simulation mode (i.e does nothing) # ' simulation ', 1, test# ' simulation ', 0, Exec$bsimulationmode = UTI Ls::readparam (' simulation ', 1, true); $oMyChange = Null;if (! $bSimulationMode) {$oMyChange = Metamodel::newobject ("CMDB Change "); $oMyChange->set ("Date", Time ()); if (userrights::isimpersonated ()) {$sUserString = Dict::format (' Ui:archive_user_onbehalfof_user ', userrights::g Etrealuser (), Userrights::getuser ()); } else {$sUserString = Userrights::getuser (); } $oMyChange->set ("UserInfo", $sUserString); $oMyChange->dbinsert ();} else{echo "

Simulation Mode--no action would be performed

"; echo "

Set the parameter simulation=0 to trigger the actual execution.

";} $ad = Ldap_connect ($aConfig [' Host '], $aConfig [' Port '] or die ("Could does connect to {$aConfig [' Host ']} on port {$aConfig [ ' Port ']}! '); echo "

Connected to {$aConfig [' Host ']} on port {$aConfig [' Port ']}

\ n ";//Set version numberldap_set_option ($ad, ldap_opt_protocol_version, 3) or Die (" Could not Set LDAP PROTOCOL "); ldap_se T_option ($ad, ldap_opt_referrals,0) or die ("Could no se the LDAP referrals");//Binding to LDAP server$bd = Ldap_bind ($ad , $aConfig [' username '], $aConfig [' Password ']) or Die ("Could not Bind"); echo "

Identified as {$aConfig [' username ']}

\ n "; $sLdapSearch = $aConfig [' Ldap_query '];echo"

LDAP Query: ' $sLdapSearch '

"; $search = Ldap_search ($ad, $aConfig [' DN '], $sLdapSearch/*, $aAttribs */) or Die (" LDAP search Failed "); $entries = Ldap_g Et_entries ($ad, $search); $index = 1; $aStatistics = Array (' created ' = = 0, ' synchronized ' = 0, ' ERROR ' =&gt ; 0,); $iCreated = 0; $iSynchronized = 0; $iErrors = 0; if ($entries ["Count"] > 0) {$iITopUsers = Inituserscache (); echo "

{$entries ["Count"]} user (s) found in Active Directory, $iITopUsers (including NON-LDAP users) found in ITop.

\ n "; foreach ($entries as $key = + $aEntry) {//echo "
$key \ n ";        Print_r ($aEntry);        echo "
\ n "; if (strcmp ($key, ' count ')! = 0) {$aData = array (); foreach ($aAttribs as $sName) {$aData [$sName] = Readldapvalue ($aEntry, $sName); } if (Empty ($aData [' Mail ')]) {$aData [' mail '] = $aData [' userPrincipalName ']; try {$sAction = Processuser ($aData, $index, $aConfig, $oMyChange); } catch (Exception $e) {echo '

An error occured while processing $index: ". $e->getmessage ()."

"; $sAction = ' ERROR '; } echo " \ n "; $aStatistics [$sAction]++; $index + +; }}}else{echo "

Nothing found!

\ n "; echo "

LDAP Query was: $sLdapSearch

\ n ";} Ldap_unbind ($ad), if ($bSimulationMode) {echo '

Simulation Mode--no action was performed

";} echo "

Statistics:

"; Echo" "; foreach ($aStatistics as $sKey = + $iValue) {echo" \ n "; echo " \ n ";} echo "
$sKey$iValue
";? >root@itsm:/var/www/html/new_itop#




After the parameters are complete, run at the command line:

root@itsm:/var/www/html/new_itop# CD webservices/root@itsm:/var/www/html/new_itop/webservices# php AD_import_ accounts.php



Execute within a scheduled task;

root@itsm-demo:~# Cat/etc/crontab #/etc/crontab:system-wide crontab# Unlike any other crontab you don ' t has to run the ' crontab ' # command to install the new version when you edit this file# and files in/etc/cron.d. These files also has username fields,# that none of the other crontabs does. shell=/bin/shpath=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin# m H Dom Mon Dow user    Command17 * * * *    root    cd/&& run-parts--report/etc/cron.hourly25 6    * * *    root    test-x/usr/sbin/a Nacron | | (CD/&& run-parts--report/etc/cron.daily) 6    * * 7    root    test-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.weekly) 6    1 * *    root    test-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.monthly) #1  */24  * * *  root cd/var/www/html/itop.new /webservices/;p hp ad_import_accounts.php  >/dev/null 2>&1
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.