Solved

How could I get a value from the Active Directory(eg:name) using an ASP script

Posted on 2004-04-20
8
502 Views
Last Modified: 2011-10-03
How could I get a value from the Active Directory(eg:name) using an ASP script ,this is in an Intranet environment.
Active Directory Windows 2000
0
Comment
Question by:Mination
  • 3
  • 2
8 Comments
 
LVL 6

Expert Comment

by:pillbug22
ID: 10872060
Depends on what you want...are you wanting to retrieve a value based on a user?



Here's a VB script to pull all info about a given user name...it could be modified to be used on an ASP page instead of WSH:





' AD_query.vbs
' Selects AD info for all users (specified by criteria)
' Can be changed to select one user, members of specific OU, or
' all members in AD.


Option Explicit


Function ParseOU(strDN)
      Dim DNarray
      DNarray = Split(strDN, "=", -1, 1)
      ParseOU = Left(DNarray(3), 5)
End Function


Function ParseSubOU(strDN)
      Dim DNarray
      DNarray = Split(strDN, "=", -1, 1)
      ParseSubOU = Left(DNarray(2), 6)
End Function


Function ParseFirstName(strCN)
      Dim nameArray
      nameArray = Split(strCN, " ", -1, 1)
      ParseFirstName = nameArray(1)
End Function



Function ParseLastName(strCN)
      Dim nameArray
      nameArray = Split(strCN, " ", -1, 1)
      ParseLastName = nameArray(0)
End Function



Function GetDN(ADUserName)

      Dim ADProfileConn, ADProfileCmd, rsADProfile

      Set ADProfileConn = CreateObject("ADODB.Connection")
      ADProfileConn.Provider = "ADSDSOObject"
      ADProfileConn.Open "Active Directory Provider"
      Set ADProfileCmd = CreateObject("ADODB.Command")
      Set ADProfileCmd.ActiveConnection = ADProfileConn

                ' Change the following line to match your AD environment
      ADProfileCmd.CommandText = "SELECT distinguishedName FROM 'LDAP://dc=adserver,dc=company,dc=com' WHERE objectClass='user' AND sAMAccountName='" & LCASE(ADUserName) & "'"
      Set rsADProfile = ADProfileCmd.Execute
      
      Do While Not rsADProfile.eof
            GetDN = "LDAP://" & rsADProfile.fields("distinguishedName")
            rsADProfile.MoveNext
      Loop
      
      Set rsAdProfile = Nothing
      Set ADprofileCmd = Nothing
      ADProfileConn.Close
      Set ADProfileConn = Nothing
      
End Function



Sub queryAD(ADUserName, OutputPath)
      Dim oObject, sProp, oClass, sAdsPath
      Dim fso, myFile, a, sLine, nums

      On Error Resume Next      

            Set fso = createObject("Scripting.FileSystemObject")
      Set myFile = fso.CreateTextFile(OutputPath, true)


      ' Bind to Active Directory object.
      Set oObject = GetObject(GetDN(ADUserName))

      Set oClass = GetObject(oObject.Schema)

      ' Enumerate mandatory properties of the object.
      For Each sProp In oClass.MandatoryProperties
            sLine = "(M) " & sProp & ": "
            If IsNull(oObject.GetEx(sProp)) Then
                  sLine = sLine & ""
            Else
                  nums = oObject.GetEx(sProp)
                  For Each a In nums
                        sLine = sLine & a & " "
                  Next
            End If
            myFile.WriteLine sLine
      Next

      ' Enumerate optional properties of the object.
      For Each sProp In oClass.OptionalProperties
            sLine = "(O) " & sProp & ": "
            If IsNull(oObject.GetEx(sProp)) Then
                  sLine = sLine & ""
            Else
                  nums = oObject.GetEx(sProp)
                  For Each a In nums
                        sLine = sLine & a & " "
                  Next
            End If
            myFile.WriteLine sLine
      Next
      
End Sub

'wscript.echo("Running...")

dim saveFile, UserName

saveFile = "c:\ldap.txt"

UserName = InputBox ("UserName to display info:", "Enter UserName")
If UserName = "" Then
    MsgBox("Must enter a user name!")
    WScript.quit(1)
End If

queryAd UserName, saveFile

wscript.echo("File has ben saved to " & saveFile)

0
 

Author Comment

by:Mination
ID: 10872129
I want to be able to lookup certain values within AD via a Intranet page i.e Phone number, Mobile...
0
 
LVL 6

Expert Comment

by:pillbug22
ID: 10872238
You can use the above code to do pretty much what you want.

Just change the one line in there (commented out) to match your AD server name, then pass the username you are wanting to look up info for.

Or, you could try the following, which uses more of a SQL-type query with a returned recordset:





Function ParseOU(strDN)
      dim DNarray
      DNarray = Split(strDN, "=", -1, 1)
      ParseOU = Left(DNarray(3), 5)
End Function



Function ParseSubOU(strDN)
      dim DNarray
      DNarray = Split(strDN, "=", -1, 1)
      ParseSubOU = Left(DNarray(2), 6)
End Function



Function ParseFirstName(strCN)
      dim nameArray
      nameArray = Split(strCN, " ", -1, 1)
      ParseFirstName = nameArray(1)
End Function



Function ParseLastName(strCN)
      dim nameArray
      nameArray = Split(strCN, " ", -1, 1)
      ParseLastName = nameArray(0)
End Function



Sub DisplayADProfileInfo(ADUserName)

      ' The section below is added in order to retrieve user's info from Active Directory.
      ' If the fields which are available on the profile are changed, the following query string
      ' for AD might also have to be changed.

      Set ADProfileConn = CreateObject("ADODB.Connection")
      ADProfileConn.Provider = "ADSDSOObject"
      ADProfileConn.Open "Active Directory Provider"


      Set ADProfileCmd = CreateObject("ADODB.Command")
      Set ADProfileCmd.ActiveConnection = ADProfileConn
 
                ' Change the following line to match your AD server's name/address
                strServerPath = "dc=ADServer,dc=company,dc=com"

      ADProfileCmd.CommandText = "SELECT cn, sAMAccountName, mail, givenName, sn, distinguishedName, company, c FROM 'LDAP://" & strServerPath & "' WHERE objectClass='user' AND sAMAccountName='" & LCASE(ADUserName) & "'"

      
      wscript.echo(ADProfileCmd.CommandText)            
      set rsADProfile = ADProfileCmd.Execute


      on error resume next
      

      Set TextStream = FSO.CreateTextFile("C:\ADList.txt")
      
      do while not rsADProfile.eof
            tempVar = ""
            tempVar = tempVar & "CN: " & rsADProfile.fields("cn") & vbNewLine
            tempVar = tempVar & "SAMAccountName: " & rsADProfile.fields("sAMAccountName") & vbNewLine
            tempVar = tempVar & "Email Address: " & rsADProfile.fields("mail") & vbNewLine
            tempVar = tempVar & "Firstname: " & rsADProfile.fields("givenName") & vbNewLine
            tempVar = tempVar & "Surname: " & rsADProfile.fields("sn") & vbNewLine
            tempVar = tempVar & "Company: " & rsADProfile.fields("company") & vbNewLine
            tempVar = tempVar & "Country: " & rsADProfile.fields("c") & vbNewLine
            tempVar = tempVar & "DN: " & rsADProfile.fields("distinguishedName") & vbNewLine
            tempVar = tempVar & "OU: " & ParseSubOU(rsADProfile.Fields("distinguishedName")) & vbNewLine
            tempVar = tempVar & "----------------------------" & vbNewLine
            Set ou = GetObject("LDAP://OU=" & ParseSubOU(rsADProfile.Fields("distinguishedName")) & ",OU=" & ParseOU(rsADProfile.Fields("distinguishedName")) & "," & strServerPath)
            tempVar = tempVar & "OU: " & ParseOU(rsADProfile.Fields("distinguishedName")) & vbNewLine
            tempVar = tempVar & "Sub OU: " & ParseSubOU(rsADProfile.Fields("distinguishedName")) & vbNewLine
            tempVar = tempVar & "CN: " & ou.cn & vbNewLine
            tempVar = tempVar & "Description: " & ou.description & vbNewLine
            tempVar = tempVar & "Display Name: " & ou.displayName & vbNewLine
            tempVar = tempVar & "----------------------------" & vbNewLine
            tempVar = tempVar & "Truncated Name (use?): " & Left(ou.description, Len(ou.description)-6) & vbNewLine
            tempVar = tempVar & "----------------------------" & vbNewLine

               TextStream.WriteLine(tempVar)
               wscript.echo(tempVar)

            rsADProfile.movenext
      Loop

      TextStream.Close

      wscript.echo("Done")
      
            
End Sub


DisplayADProfileInfo("<username>")
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 3

Expert Comment

by:Level10Access
ID: 10872779
Hey,

Just to let you know, you should be VERY careful when writing this code from a security standpoint. Use a great amount of input validation and only let the user input what YOU want them to input. Tricky people can use whats known as LDAP injection to get any information on any object in Active Directory.

Good Luck Mate!
0
 

Author Comment

by:Mination
ID: 10873074
Thanks for the Info! Well I must be dumb, I have changed the `strServerPath = "dc=luzifer,dc=mination,dc=net"` to reflect my server but i just get nothing back.

I am just going to a prompt and typing in "DisplayADProfileInfo username"

As you guessed I have never done this before :(

How would i turn this into a webpage if i get it working?
0
 
LVL 6

Accepted Solution

by:
pillbug22 earned 50 total points
ID: 10877718
Both of these should run from within Window (without the command prompt).  The first one will open a prompt to ask you for the user to return info for, and the second will require you to change the function call (last line of the code).  Just double-clicking them should open them no problem (assuming you have Windows Scripting Host installed.  If not, you can d/l from MS, r just convert it to an ASP page).

Converting to an ASP should be simple, it's just replacing the items that write to a text file to a response.write (or however you want it).

For example, you could have the following .asp file.  You would just need to include this file on your page, then call the DisplayADProfileInfo(logonUser) function (passing the userName of the user you want to return info for), and it do the processing for you.

Sorry there's lots of comments in there; I've changed up the requirements for the page I pulled this from...but it should give you an idea of all the different things you can do with the recordset that is returned from your LDAP query.




<%
' **************
' inc_AD_Profile.asp
' **************

Function ParseOU(strCN)
      dim CNarray
      CNarray = Split(strCN, "=", -1, 1)
      ParseOU = Left(CNarray(3), 5)
End Function


Function ParseSubOU(strCN)
      dim CNarray
      CNarray = Split(strCN, "=", -1, 1)
      ParseSubOU = Left(CNarray(2), 6)
End Function


Function ParseFirstName(strCN)
      dim nameArray
      nameArray = Split(strCN, " ", -1, 1)
      ParseFirstName = nameArray(1)
End Function


Function ParseLastName(strCN)
      dim nameArray
      nameArray = Split(strCN, " ", -1, 1)
      ParseLastName = nameArray(0)
End Function


Sub DisplayADProfileInfo(logonUser)

      ' The section below is added in order to retrieve user's info from Active Directory.
      ' If the fields which are available on the profile are changed, the following query string
      ' for AD might also have to be changed.

      Set ADProfileConn = Server.CreateObject("ADODB.Connection")
      ADProfileConn.Provider = "ADSDSOObject"
      
      
      ADProfileConn.Open "ADs Provider"
                ' Change the following to match your LDAP Server path following the "dc=" format
                strServerPath = "dc=corpAD,dc=company,dc=com"

      strADCmd = "SELECT AdsPath, cn, mail, givenName, sn, l, st, c FROM 'LDAP://" & strServerPath & "' WHERE objectClass='user' AND sAMAccountName='" & logonUser & "'"
      
      set rsADProfile = adProfileConn.Execute(strADCmd)

      ' ********** Show each returned item/type **********
      'For each fld in rsADProfile.Fields
      '      response.write fld.Name & ", " & fld.Type & "<br>"
      'Next
      ' **************************************************

      'response.write "<br><br>"

      rsADProfile.MoveFirst
      
      Dim longName, lastName, firstName, email, location, state, country, c, company, arrCN, arrLN, arrFN, arrEmail
      
      ' ********** Store last name **********
      If IsNull(rsAdProfile.Fields("sn")) then
            arrCN = rsAdProfile.Fields("cn").Value
            longName = CStr(arrCN(0))
            session("ADlastName") = ParseLastName(CStr(longName))
      Else
            arrLN = rsAdProfile.Fields("sn").Value
            lastName = CStr(arrLN(0))
            session("ADlastName") = CStr(lastName)
      End If
      'response.Write session("lastName") & "<br>"
      ' *************************************

      ' ********** Store first name **********
      If IsNull(rsAdProfile.Fields("givenName")) then
            arrCN = rsAdProfile.Fields("cn").Value
            longName = CStr(arrCN(0))
            session("ADfirstName") = ParseFirstName(CStr(longName))
      Else
            arrFN = rsAdProfile.Fields("givenName").Value
            firstName = CStr(arrFN(0))
            session("ADfirstName") = CStr(firstName)
      End If
      'response.Write session("firstName") & "<br>"
      ' **************************************
      
      ' ********** Store email **********
      If IsNull(rsAdProfile.Fields("givenName")) then
            session("ADemail") = ""
      Else
            arrEmail = rsAdProfile.Fields("mail").Value
            email = CStr(arrEmail(0))
            session("ADemail") = CStr(email)
      End If
      'response.Write session("email") & "<br>"
      ' *********************************
      
      ' ********** Store city ***********
      If IsNull(rsAdProfile.Fields("l")) then
            session("ADcity") = ""
      Else
            arrL = rsAdProfile.Fields("l").Value
            location = CStr(arrL(0))
            session("ADcity") = CStr(location)
      End If
      'response.Write session("location") & "<br>"
      ' *********************************
      
      ' ********** Store state **********
      If IsNull(rsAdProfile.Fields("st")) then
            session("ADstate") = ""
      Else
            arrState = rsAdProfile.Fields("st").Value
            state = CStr(arrState(0))
            session("ADstate") = CStr(state)
      End If
      'response.Write session("location") & "<br>"
      ' *********************************
      
      ' ********** Store country ********
      If IsNull(rsAdProfile.Fields("c")) then
            session("ADcountry") = ""
      Else
            session("ADcountry") = rsAdProfile.Fields("c")
            'arrCountry = rsAdProfile.Fields("c").Value
            'country = CStr(arrCountry(0))
            'session("ADcountry") = CStr(country)
      End If
      'response.Write session("location") & "<br>"
      ' *********************************
      
      ' ********* Store facility ********
      'If IsNull(rsAdProfile.Fields("company")) then
      '      Response.Write "<script>alert('Company is null');</script>"
      '      session("ADfacility") = ""
      'Else
      '      Response.Write "<script>alert('Company is NOT null');</script>"
      '      arrCompany = rsAdProfile.Fields("company").Value
      '      company = CStr(arrCompany(0))
      '      session("ADfacility") = CStr(company)
      'End If
      'response.Write session("location") & "<br>"
      ' *********************************
            
      'response.Write "<br><br>"
      
      ' ********** Show all returned name/values from search **********
      'While Not rsADProfile.EOF
      '      For each fld in rsADProfile.Fields
      '            'Check for multi-value attribute
      '            If IsNull(fld.Value) then
      '                  'Return Null Value attribute
      '                  response.write fld.Name & " = (empty)<br>"
      '            Else
      '                  If fld.Type = 12 Then                                                      '12 means adVariant/array
      '                        'Return multi-value attribute(array)
      '                        response.write fld.Name & " = "
      '
      '                        'Need to assign current field to a variable.
      '                        'For some reason, cannot access recordset.field.value as
      '                        'an array, but once assigned to a variable, that variable
      '                        'can be access like an array
      '                        dim arrFld
      '                        arrFld = fld.Value
      '                        For j = LBound(arrFld) To UBound(arrFld)
      '                              response.Write CStr(arrFld(j)) & ","
      '                        Next
      '                        response.Write "<br>"
      '                  Else
      '                        'Return Single Value attribute
      '                        response.write fld.Name & " = " & CStr(fld.Value) & "<br>"
      '                  End If
      '            End If
      '      Next
      '      rsADProfile.MoveNext
      'Wend
      ' **************************************************************

End Sub

%>
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This is about my first experience with programming Arduino.
Find out how to use Active Directory data for email signature management in Microsoft Exchange and Office 365.
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now