No announcement yet.

LDAP Script Display Information from Active Directory

  • Filter
  • Time
  • Show
Clear All
new posts

  • LDAP Script Display Information from Active Directory

    Basically I am a newbie to some scripting but I have tried some scripts with variable success. Basicallly what I would like to do is make a company directory (HTML or some other webbased process) that auto updates from active directory through the form of LDAP (or any other kinda that you all can suggest) A directory that contained items such as name, email, phone, etc. We are on a 2003 network so I know that the LDAP has to be binding. Any ideas or at least a good push in the right direction? I have tried other's scripts and either it pulled all the information from activate directory or just a single user. Also is there a way to include this script information in a webpage formatted that way it can have a readable look to it?

    THANK YOU SO MUCH FOR YOUR TIME IN READING THIS I really do appreciate it!

    Chase D

  • #2
    Re: LDAP Script Display Information from Active Directory

    I haven't the time to write it completly for you, so you need do somewhat youreself.

    However, if you can read the information from 1 user, you can loop it until you got you're selection or completly through AD.
    And yes, if you script it right, you can put it into a HTML format, or pushing it to IE.

    Start somewhat with the scripts you already found and place the url's of those.
    From that point, it's easier to help you further with it.
    Technical Consultant

    "No matter how secure, there is always the human factor."

    "Enjoy life today, tomorrow may never come."
    "If you're going through hell, keep going. ~Winston Churchill"


    • #3
      Re: LDAP Script Display Information from Active Directory

      Well I didn't go back to refind my research but here are some examples of what I have found on the net and have modified slightly (modified as in specific to my domain)

      $ldap_host = "";
      $base_dn = "DC=re-bath,DC=local";
      $filter = "(cn=administrator)";
      $ldap_user = "CN=administrator,OU=MyBusiness,DC=re-bath,DC=local";
      $ldap_pass = "PASSWORD";
      $connect = ldap_connect( $ldap_host, $ldap_port)
      or exit(">>Could not connect to LDAP server<<");
      ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
      ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
      $bind = ldap_bind($connect, $ldap_user, $ldap_pass)
      or exit(">>Could not bind to $ldap_host<<");
      $read = ldap_search($connect, $base_dn, $filter)
      or exit(">>Unable to search ldap server<<");
      $info = ldap_get_entries($connect, $read);
      echo $info["count"]." entries returned<p>";
      for ($i=0; $ii<$info[$i]["count"]; $ii++){
      $data = $info[$i][$ii];
      echo $data.":&nbsp;&nbsp;".$info[$i][$data][0]."<br>";

      --------------------------------------- END

      So this does connect, but it does not search in a tree format, it seems that it only searches the OU that is stated and does not search the sub ou's. Also it seems that it does grab ALL the informaton in AD. Also it seems like I have to actually input the username hence bolded portion in the script. I will display 2 examples of results. 1st example is of the user administrator who is in the MyBusiness OU. The 2nd example is searching for the wildcard *. FYI I have taken out some information and replaced it with all capital general words

      ------------Searching Administrator

      1 entries returned
      objectclass: top
      cn: Administrator
      sn: Admin
      description: Built-in account for administering the computer/domain
      physicaldeliveryofficename: Office
      givenname: Admin
      distinguishedname: CN=Administrator,OU=MyBusiness,DC=re-bath,DC=local
      instancetype: 4
      whencreated: 20050520143904.0Z
      whenchanged: 20060803190110.0Z
      displayname: Administrator
      usncreated: 8194
      memberof: CN=ALL,OU=SBSUsers,OU=Users,OU=MyBusiness,DC=re-bath,DC=local
      usnchanged: 132281
      altrecipient: CN=John N Britton IV,OU=Users,OU=MyBusiness,DC=re-bath,DC=local
      homemta: CN=Microsoft MTA,CN=SERVER1,CN=Servers,CN=first administrative group,CN=Administrative Groups,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=re-bath,DC=local
      deliverandredirect: TRUE
      proxyaddresses: smtp:[email protected]
      extensionname: 5717D53E-DD6D-4d1e-8A1F-C7BE620F65AA:L
      homemdb: CN=Mailbox Store (SERVER1),CN=First Storage Group,CN=InformationStore,CN=SERVER1,CN=Servers,CN =first administrative group,CN=Administrative Groups,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=re-bath,DC=local
      mdbusedefaults: TRUE
      mailnickname: Administrator
      name: Administrator
      objectguid: P(aG• #u"
      useraccountcontrol: 66048
      badpwdcount: 0
      codepage: 0
      countrycode: 0
      badpasswordtime: 127991432468150000
      lastlogoff: 0
      lastlogon: 127991432502368750
      scriptpath: SBS_LOGIN_SCRIPT.bat
      pwdlastset: 127925358877187500
      primarygroupid: 513
      admincount: 1
      accountexpires: 9223372036854775807
      logoncount: 373
      samaccountname: Administrator
      samaccounttype: 805306368
      showinaddressbook: CN=Default Global Address List,CN=All Global Address Lists,CN=Address Lists Container,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=re-bath,DC=local
      legacyexchangedn: /o=First Organization/ou=first administrative group/cn=Recipients/cn=Administrator
      objectcategory: CN=Person,CN=Schema,CN=Configuration,DC=re-bath,DC=local
      iscriticalsystemobject: TRUE
      dscorepropagationdata: 20060801221508.0Z
      lastlogontimestamp: 127991052707837500
      textencodedoraddress: c=US;a= ;p=First Organizati;o=Exchange;s=Administrator;
      mail: [email protected]
      msexchhomeservername: /o=First Organization/ou=first administrative group/cn=Configuration/cn=Servers/cn=SERVER1
      msexchalobjectversion: 82
      msexchuseraccountcontrol: 0
      msexchmailboxguid: ּfŸ6L ,‡
      msexchpoliciesincluded: {DC31BB33-C04A-41AB-A7BD-80F16CB2A14B},{3B6813EC-CE89-42BA-9442-D87D4AA30DBC}

      -----------------------Searching *
      313 entries returned
      objectclass: top
      cn: {0227ED4A-3422-4690-9D06-530A65A1E0D8}
      distinguishedname: CN={0227ED4A-3422-4690-9D06-530A65A1E0D8},CN=Policies,CN=System,DC=re-bath,DC=local
      instancetype: 4
      whencreated: 20050521175846.0Z
      whenchanged: 20060519181129.0Z
      displayname: Small Business Server Internet Connection Firewall
      usncreated: 22894
      usnchanged: 40998
      showinadvancedviewonly: TRUE
      name: {0227ED4A-3422-4690-9D06-530A65A1E0D8}
      objectguid: 2i†YI9| ?P
      flags: 0
      versionnumber: 2
      objectcategory: CN=Group-Policy-Container,CN=Schema,CN=Configuration,DC=re-bath,DC=local
      gpcfunctionalityversion: 2
      gpcfilesyspath: \\re-bath.local\SysVol\re-bath.local\Policies\{0227ED4A-3422-4690-9D06-530A65A1E0D8}
      gpcmachineextensionnames: [{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{35378EAC-683F-11D2-A89A-00C04FBBCFA2}]
      gpcwqlfilter: [re-bath.local;{FCF9D148-AE4E-40EC-90BD-02628D032BC6};0]

      I hope that this has provided some example. Ideally I would like it to look like an address book once I figure out how to put in the html. Listed the AD information in like an address book sort of sense.

      Thank you so much for your time in reading this,


      • #4
        Re: LDAP Script Display Information from Active Directory

        1. Put this in an ASP page (index.asp)
        <%@ Language=VBScript %>
        <% StartTime = Timer %>
        <!--#include file = ""-->
        <head><title><%=strCompany%> - Intranet PhoneBook</title>
        Dim objRootDSE, objConnection, objRecordSet, objCommand
        Dim strDomainLDAP, intPage, i, j, strTRbgColor, strTemp
        Const ADS_SCOPE_SUBTREE = 2
        Set objRootDSE = GetObject("GC://RootDSE")
        strDomainLDAP = objRootDSE.Get("DefaultNamingContext")
        Set objRootDSE = Nothing
        Set objConnection = CreateObject("ADODB.Connection")
        Set objRecordSet = Server.CreateObject("ADODB.Recordset")
        Set objCommand = Server.CreateObject("ADODB.Command")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Open "Active Directory Provider"
        Set objCommand.ActiveConnection = objConnection
        objCommand.Properties("Page Size") = 1000
        objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
        objCommand.CommandText = "SELECT Name, mail, physicalDeliveryOfficeName, telephoneNumber" & _
        			" FROM 'LDAP://" & strDomainLDAP & "' WHERE objectCategory='user' ORDER BY Name"
        objRecordSet.Open objCommand.CommandText, objConnection,1,1
        objRecordSet.PageSize = Cint(RowsPerPage)
        If Request.QueryString("page") = "" Then
        	intPage = 1
        	intPage = Request.QueryString("page")
        End If
        If objRecordSet.EOF Then 
        	Response.Write "<h3>Error</h3>" & vbCrLf
        	Response.Write "<center><h3>" & strCompany & " - PhoneBook </h3>" & vbCrLf
        	objRecordSet.AbsolutePage = intPage
        	Response.Write "<table align=center border=1>" & vbNewLine
        	Response.Write "	<tr align=center>" & vbNewLine
        	For i = 0 To objRecordSet.Fields.Count - 1
        		Response.Write "		<th>" & objRecordSet.Fields(i).Name & "</th>" & vbNewLine
        	Response.Write "	</tr>" & vbNewLine
        	For j = 1 To objRecordSet.PageSize
        		Response.Write "	<tr bgColor='"
        		strTRbgColor = RowOddColor
        		If j Mod 2 = 0 Then strTRbgColor = RowEvenColor
        		Response.Write strTRbgColor 
            	If RowMoveColor <> "" Then
            		Response.Write "' onmouseover=this.bgColor='" & RowMoveColor & "' onmouseout=this.bgColor='" & strTRbgColor
            	End If
            	Response.Write "'>" & vbCrLf		
        		For i = 0 To objRecordSet.Fields.Count - 1
        			strTemp = "<font color=" & strTRbgColor & ">-</font>"
        			If objRecordSet.Fields(i).Value <> "" Then strTemp = objRecordSet.Fields(i).Value
        			Response.Write "		<td>" & strTemp & "</td>" & vbNewLine
        		Response.Write "	</tr>" & vbNewLine
        	Response.Write "</table>" & vbNewLine
        	Response.Write "<br><br>" & vbNewLine	
        	If Cint(intPage) = 1 Then
        		Response.Write "<font color=silver>First</font>&nbsp;" & vbNewLine
        		Response.Write "<font color=silver>Prev</font>&nbsp;" & vbNewLine
        		Response.Write "<a href=" & ASPPage & "?" & TrimServerVariable("page=1&" & Request.ServerVariables(31).Item) & ">First</a>&nbsp;" & vbNewLine
        		Response.Write "<a href=" & ASPPage & "?" & TrimServerVariable("page=" & intPage - 1 & "&" & Request.ServerVariables(31).Item) & ">Prev</a>&nbsp;" & vbNewLine
        	End If
        	If Cint(intPage) = objRecordSet.PageCount Then
        	Response.Write "<font color=silver>Next</font>&nbsp;" & vbNewLine
        		Response.Write "<font color=silver>Last</font>&nbsp;" & vbNewLine
        		Response.Write "<a href=" & ASPPage & "?" & TrimServerVariable("page=" & intPage + 1 & "&" & Request.ServerVariables(31).Item) & ">Next</a>&nbsp;" & vbNewLine
        		Response.Write "<a href=" & ASPPage & "?" & TrimServerVariable("page=" & objRecordSet.PageCount & "&" & Request.ServerVariables(31).Item) & ">Last</a>&nbsp;" & vbNewLine
        	End If
        	Response.Write "</center>" & vbNewLine
        Set objRecordSet = Nothing
        Set objConnection = Nothing
        End If
        Private Function TrimServerVariable(strString)
        Dim temp 'As String
        If inStr(strString,"&") <> 0 Then
        	arr = Split(strString, "&")
        	strString = ""
        	For i = 0 To UBound(arr) - 1
                temp = Left(arr(i), InStr(arr(i), "="))
        		If InStr(strString, temp) = 0 Then
        		strString = strString & arr(i) & "&"
        		End If
        	strString = Left(strString, Len(strString) - 1)
        End If
        TrimServerVariable = strString
        End Function
        EndTime = Timer
        Response.Write "<!-- Page rendered in " & (EndTime-StartTime) & " -->" & vbNewLine
        2. Create a text file named "" and paste this into it:
        ASPPage = "index.asp"
        Const strCompany = "Company"
        RowsPerPage = "10"
        RowOddColor = "#EFEFEF"
        RowEvenColor = "#DCDCDC"
        RowMoveColor = "yellow"
        3. Put the 2 files in a virtual directory in IIS, and give it a try...


        • #5
          Re: LDAP Script Display Information from Active Directory

          Thank you. I will try this out within 48 hours and report back.


          • #6
            Re: LDAP Script Display Information from Active Directory

            I had to do a little research on ways to get ASP working correctly such as turning off anonymous access, etc. As you for your code though, it works Very, Very, Very nice. It displays the information in a readable manner. It displays everything I could and I even like the whole flipping pages thing. Few questions my friend, I noticed that maybe it does not authenticate or something of that nature when I try to load up the page from another computer.

            For example:
            On the server that is hosting the web page, the directory works fine. When I access it from another computer say that Domain Controller, I receive a 500 (internal) error. I believe it is because it might now be authenticating the user???? I have enabled integrated authenticated and basic authentication. Do you think if I were to hard code a username and password it would stop this?

            Eitherway I just want to give a very large BRAVO to you once again. This is a fantastic job.


            • #7
              Re: LDAP Script Display Information from Active Directory

              There is no need to hard code the username (nor the password)...
              instead of it, use Anonymous Access for the virtual folder (or web site)
              type-in the domain user and it's password in the text box - see snapshot.
              don't forget to uncheck all other authentication mothods (basic / digest / etc')

              good luck,
              BTW - I'm glad you liked it...
              Attached Files


              • #8
                Re: LDAP Script Display Information from Active Directory

                Thanks for the great script. I have one issue though. I want to only display users who have e-mail addresses associated with them. I have some service accounts which I do not want to display.

                I assume there is some sort of logic associated with that attribute being null, but don't know how to script that logic.

                Also, is there a way to make the e-mail address hyperlinked to allow someone to click on the name to launch their default mail app to send a message?


                • #9
                  Re: LDAP Script Display Information from Active Directory

                  I just started using this script on our Intranet page and it works great! A few things I'd like to do with it (I'm a hardware guy, so programming is generally lost on me ):

                  - Display only users with phone extensions
                  - One specific OU (right now it's pulling all Users from the entire directory)
                  - Possible to display multiple tables per page? In other words, instead of:

                  Name1  Phone1  Dept1
                  Name2  Phone2  Dept2
                  Name3  Phone3  Dept3
                  Name4  Phone4  Dept4
                  Name5  Phone5  Dept5
                  Name6  Phone6  Dept6
                  Do something like:

                  Name1  Phone1  Dept1      Name3  Phone3  Dept3      Name5  Phone5  Dept5
                  Name2  Phone2  Dept2      Name4  Phone4  Dept4      Name6  Phone6  Dept6
                  Also, when I get to the last page, I get the following error:
                  ADODB.Field error '800a0bcd' 
                  Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record. 
                  /phonebook.asp, line 66
                  Last edited by JW; 4th September 2007, 18:44.


                  • #10
                    Re: LDAP Script Display Information from Active Directory

                    I am trying to use this script. I run ASP pages on my site. but my IIS is in a different server then the Active directory ( I am not sure if that matters or not). But i get the following error:

                    Provider error '80040e37'

                    Table does not exist.

                    /Emp/index.asp, line 31

                    I actually use another asp code to get my info but that page uses hard coded username and password. and i don't want to do that.

                    here is my code:

                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
                    <html xmlns="">
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                    <title>BG Service Solutions Hub- MIS Support</title>
                    <link href="../../css/style.css" type="text/css" rel="stylesheet" media="all" />
                    <link href="../../css/print.css" type="text/css" rel="stylesheet" media="print"/>
                     <div id="body">
                    <div class="main no-right no-left">
                    <span class="dontprinttext">
                    	<h1>Welcome to the Employee Information Page</h1>
                    		<div class="indent">
                    Dim oRootDSE, oCon, oCmd, oRecordSet
                    Dim sDomainADsPath, sProperties, sUser, sPassword, sCounter
                    Dim strLName, strFName, strAccount, strEMail, strSearch, strPerson, strFLname
                    	  strName = Trim(Request("Name"))
                          strDep = Trim(Request("Dep"))
                          strCom = Trim(Request("Comp"))
                          strTitle = Trim(Request("Title"))
                    		if strCom = "" then
                    		end if
                    		if strDep ="" then
                    		end if
                    Set oRootDSE = GetObject("LDAP://RootDSE")
                    sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
                    ''Response.Write strDep
                    Set oRootDSE = Nothing
                    Set oCon = Server.CreateObject("ADODB.Connection")
                    sUser = "bgnet\*****" ''A valid Active Directory account
                    sPassword = "*************" ''The valid pass word for the above account
                    oCon.Provider = "ADsDSOObject"
                    oCon.Open "ADProvider", sUser, sPassword
                    Set oCmd = Server.CreateObject("ADODB.Command")
                    Set oCmd.ActiveConnection = oCon
                    oCmd.CommandText = "select SN, GivenName, mail, sAMAccountName, telephonenumber, displayName, "
                    oCmd.CommandText = oCmd.CommandText & "physicaldeliveryofficename, streetAddress, l, st, postalcode, "
                    oCmd.CommandText = oCmd.CommandText & "title, department, company, manager "
                    oCmd.CommandText = oCmd.CommandText & "from '" & sDomainADsPath & "' WHERE objectCategory = 'person' AND "
                    oCmd.CommandText = oCmd.CommandText & "objectClass = 'user' "
                    oCmd.CommandText = oCmd.CommandText & "AND SN = '" & strName & "*' "
                    oCmd.CommandText = oCmd.CommandText & "AND department='" & strDep & "' "
                    oCmd.CommandText = oCmd.CommandText & "AND company='" & strCom & "' "
                    oCmd.CommandText = oCmd.CommandText & "AND title='" & strTitle & "*' "
                    oCmd.CommandText = oCmd.CommandText & "Order by SN"
                    ''response.write ocmd.CommandText
                    ''oCmd.Properties("Page Size") = 100
                    Set oRecordSet = oCmd.Execute
                    ''Response.Write sDomainADsPath
                    Response.Write "&nbsp;"
                    sCounter = 0
                    While Not oRecordSet.EOF
                    	if sCounter = 0 then
                    		<span class="printtext">
                    			<h1>Welcome To Employee Information Page</h1>
                    			<h2> Employee Information Result </h2>
                    	End If
                    Response.Write "<Table border='0' id='mytable' cellpadding='0' cellspacing='0'>"
                    	Response.Write "<tr><th align='left' width='40%'>"
                    	Response.Write "Name"
                    	Response.Write "</th>"
                    	Response.Write "<th width='30%'>"
                    	Response.Write "EMail"
                    	Response.Write "</th><th width='30%'>"
                    	Response.Write "Telephone"
                    	Response.Write "</th></tr>"
                    Response.Write "<Tr><Td><font size='3' name='Verdana'><b>"
                    Response.Write oRecordSet.Fields("SN")
                    Response.Write ", "
                    Response.Write oRecordSet.Fields("GivenName")
                    Response.Write "&nbsp;</b></font>"
                    Response.Write "</td><td>"
                    Response.Write "<a href='mailto:" & oRecordSet.Fields("mail")
                    Response.Write "'>"
                    Response.Write lcase(oRecordSet.Fields("mail"))
                    Response.Write "</a>"
                    Response.Write "&nbsp;"
                    Response.Write "</td><td>"
                    Response.Write oRecordSet.Fields("telephonenumber")
                    Response.Write "&nbsp;"
                    Response.Write "</td></tr>"
                    	Response.Write "<th>"
                    	Response.Write "Physical"
                    	Response.Write "</th><th  colspan='2'>"
                    	Response.Write "Address"
                    	Response.Write "</th></tr>"
                    Response.Write "<tr><td>"
                    Response.Write oRecordSet.Fields("physicaldeliveryofficename")
                    Response.Write "&nbsp;"
                    Response.Write "</td><td colspan='2'>"
                    Response.Write oRecordSet.Fields("streetAddress")
                    Response.Write "&nbsp;"
                    Response.Write oRecordSet.Fields("l")
                    Response.Write "&nbsp;"
                    Response.Write oRecordSet.Fields("st")
                    Response.Write "-"
                    Response.Write oRecordSet.Fields("postalcode")
                    Response.Write "</td></tr>"
                    	Response.Write "<tr><th>"
                    	Response.Write "Title"
                    	Response.Write "</th><th>"
                    	Response.Write "Department"
                    	Response.Write "</th><th>"
                    	Response.Write "Company"
                    	Response.Write "</th></tr>"
                    Response.Write "<tr><td>"
                    Response.Write oRecordSet.Fields("title")
                    Response.Write "&nbsp;"
                    Response.Write "</td><td>"
                    Response.Write oRecordSet.Fields("department")
                    Response.Write "&nbsp;"
                    Response.Write "</td><td>"
                    Response.Write oRecordSet.Fields("company")
                    Response.Write "&nbsp;"
                    Response.Write "</td></tr>"
                    Response.Write "</Table> &nbsp;"
                    if sCounter = 1 Then
                    Response.Write "<span class='printtext'>"
                    	Response.Write "<p style='page-break-before: always'> </p>"
                    Response.Write "</span>	"
                    	sCounter = 0
                    	sCounter = sCounter + 1
                    End If
                    Set oRecordSet = Nothing
                    Set oCon = Nothing
                    <span class="dontprinttext">
                    <Table width="95%">
                    		<td align="right">
                    			<input type="button" value="Back" onClick="history.go(-1)">
                    	<div id="footer">
                    	&copy; Copyright <a href="mailto:[email protected]">BG Service Solutions</a> 2007<br />
                    <br />
                    <span class="printtext">
                    <Table width="95%">
                    		<td align="center">
                            &copy; Copyright BG Service Solution 2007
                    Please please help me out here... btw i am very new at this... thanks
                    Last edited by akabir77; 3rd October 2007, 22:30.


                    • #11
                      Re: LDAP Script Display Information from Active Directory

                      Ok, guys I am in same problem. When I uncheck Anonymous access then it shows

                      Provider (0x80040E37)
                      Table does not exist.

                      If I chek Anonymous acces then its ok. But other client will access my PC through browser so I can't check Anonymous access. Pls help me is there any alternative option ?



                      • #12
                        Re: LDAP Script Display Information from Active Directory

                        over a year later and my thread is still bein used... coolio!


                        • #13
                          Re: LDAP Script Display Information from Active Directory

                          Ok, Man............

                          Have u found this solution? pls let me know


                          • #14
                            Re: LDAP Script Display Information from Active Directory

                            Originally posted by homeshark View Post
                            over a year later and my thread is still bein used... coolio!
                            Can close it if you like.
                            Joined: 23rd December 2003
                            Departed: 23rd December 2015