Jump to content

LDAP canonical name query


Recommended Posts

  • Developers

Hi guys!

I´m working on a script to update some object properties of Active Directory.

I needs a way to query the Active Directory and gets the canonical name of the object (Ex. LDAP://cn=rdp,ou=SERVERS,ou=AREA,dc=test,dc=net

Some one can help?

tks

Pierre

What information do you have that you want to retrieve the canonical name for ?

MAybe this will give you an idea: This is a Func I use to retrieve user information from the AD. When there is an exact match it will return the found user info and when multiple users are found it will show a GUI with the list you can select from.

#include <GUIConstants.au3>
#include <GUIListView.au3>
Global $UserId = ""
Global $UserDomain = "dc=your,dc=dom"
Global $UserName = ""
Global $UserLongName = ""
Global $UserDN = ""
;
_EnumUsers("YourDomain","A")
ConsoleWrite('$UserId = ' & $UserId & @lf & '>Error code: ' & @error & @lf);### Debug Console
ConsoleWrite('$UserName = ' & $UserName & @lf & '>Error code: ' & @error & @lf);### Debug Console
ConsoleWrite('$UserLongName = ' & $UserLongName & @lf & '>Error code: ' & @error & @lf);### Debug Console
ConsoleWrite('$UserDN = ' & $UserDN & @lf & '>Error code: ' & @error & @lf);### Debug Console
;
Exit

Func _EnumUsers($IDomain, $l_UserId)
   ; 
    $Found_Users = ""
    $H2_Search = GUICreate("Select User", 700, 500, Default, Default)
    $h_msg = GUICtrlCreateLabel("Searching .... one moment", 5, 5, 200, 40)
    GUICtrlSetColor(-1, 0xff0000)
    GUICtrlSetFont(-1, 10, 800)
    $h_LV = GUICtrlCreateListView("Found users names | Fullname |DN ", 5, 35, 680, 400)
    _GUICtrlListViewSetColumnWidth ($h_LV, 0, 120) 
    _GUICtrlListViewSetColumnWidth ($h_LV, 1, 200) 
    _GUICtrlListViewSetColumnWidth ($h_LV, 2, 600) 
    $Counter = 0
    GUISetCursor(15, Default, $H2_Search)
    Local $objCommand = ObjCreate("ADODB.Command")
    Local $objConnection = ObjCreate("ADODB.Connection")
    $objConnection.Provider = "ADsDSOObject"
    $objConnection.Open ("Active Directory Provider")
    $objCommand.ActiveConnection = $objConnection
    Local $strBase = "<GC://" & $UserDomain & ">"
    Local $strFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & $l_UserId & "*))"
    Local $strAttributes = "cn,sAMAccountName,displayName,sn,distinguishedName"
    Local $strQuery = $strBase & ";" & $strFilter & ";" & $strAttributes & ";subtree"
    $objCommand.CommandText = $strQuery
    $objCommand.Properties ("Page Size") = 100
    $objCommand.Properties ("Timeout") = 30
    $objCommand.Properties ("Cache Results") = False
    $ADS_SCOPE_SUBTREE = 2
    $objCommand.Properties ("searchscope") = $ADS_SCOPE_SUBTREE
    Local $objRecordSet = $objCommand.Execute
    While Not $objRecordSet.EOF
        $strName = $objRecordSet.Fields ("sAMAccountName").Value
        $strCN = $objRecordSet.Fields ("cn").value
        $strdisplayName = $objRecordSet.Fields ("displayName").value
        $strSN = $objRecordSet.Fields ("SN").value
        $strdistinguishedName = $objRecordSet.Fields ("distinguishedName").value
        $Counter = $Counter + 1
        if $Counter = 2 then    GUISetState(@SW_SHOW, $H2_Search)
        If $Counter > 500 Then ExitLoop
        GUICtrlCreateListViewItem($strName & "|" & $strCN & "|" & $strdistinguishedName, $h_LV)
        $objRecordSet.MoveNext
    WEnd
    $objConnection.Close
    GUISetCursor(2, Default, $H2_Search)
    If $Counter > 500 Then
        GUICtrlSetData($h_msg, "Showing First 500 records. Select user to process")
    Else
        GUICtrlSetData($h_msg, "Select user to process")
    EndIf
    GUICtrlSetColor($h_msg, 0x000000)
    $H2_Ok = GUICtrlCreateButton("Ok", 265, 450, 60, 30, $BS_DEFPUSHBUTTON)
    $H2_Cancel = GUICtrlCreateButton("Cancel", 375, 450, 60, 30)
   ; Check if any match is found
    If $Counter = 0 Then
        Return ""
    EndIf
    $MouseDown = 0
   ; If only 1 found than assume it the one wanted
    If $Counter = 1 Then
        GUIDelete($H2_Search)
        $UserId = $strName
        $UserName = $strdisplayName
        $UserDN = $strdistinguishedName
        Return $strName
    EndIf
   ;
    While 1
        $msg = GUIGetMsg($H2_Search)
        If $msg = 0 Then ContinueLoop
        If $msg = $GUI_EVENT_CLOSE Or $msg = $H2_Cancel Then
            GUIDelete($H2_Search)
            Return ""
        EndIf
        If $msg = $H2_Ok Then
           ; retrieve selected username
            $SelectLine = StringSplit(GUICtrlRead(GUICtrlRead($h_LV)), "|")
            If $SelectLine[0] = 3 Then
                $UserId = $SelectLine[1]
                $UserName = $SelectLine[2]
                $UserDN = $SelectLine[3]
                GUIDelete($H2_Search)
                Return $SelectLine[1]
            EndIf
        EndIf
       ; check for Doubleclick
        If $msg = $GUI_EVENT_PRIMARYDOWN Then
            If $MouseDown = 0 Then
                $MouseDown = TimerInit()
            Else
               ; cliked twice within 400 ms thus selected this entry
                If TimerDiff($MouseDown) < 400 Then
                   ; retrieve selected username
                    $SelectLine = StringSplit(GUICtrlRead(GUICtrlRead($h_LV)), "|")
                    If $SelectLine[0] = 3 Then
                        $UserId = $SelectLine[1]
                        $UserName = $SelectLine[2]
                        $UserDN = $SelectLine[3]
                        GUIDelete($H2_Search)
                        Return $SelectLine[1]
                    EndIf
                EndIf
            EndIf
        EndIf
       ; Reset count when time between clicks is longer than 400ms
        If $MouseDown > 0 And TimerDiff($MouseDown) > 400 Then $MouseDown = 0
    WEnd
EndFunc  ;==>_EnumUsers

EDIT: Updated ... (tnx big_daddy)

Edited by JdeB

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Thaks JdeB

What I reealy needs is to update the EmploeeyID property of an user, and I just have the username.

Your Function retrieves the DN. Is that I needs.

Initialy I think to use LDIFDE to update this property, but.... is possible to do just using AutoIT?

Thanks again

Pierre

Link to comment
Share on other sites

  • Developers

Thaks JdeB

What I reealy needs is to update the EmploeeyID property of an user, and I just have the username.

Your Function retrieves the DN. Is that I needs.

Initialy I think to use LDIFDE to update this property, but.... is possible to do just using AutoIT?

Thanks again

Pierre

Cannot test this one but it should be close to what you want :

$IDomain = "??"
$IUserId = "??"
$IEmpId = "??" 
;
Const $ADS_UF_SCRIPT = 0x0001
Const $ADS_UF_ACCOUNTDISABLE = 0x0002
Const $ADS_UF_HOMEDIR_REQUIRED = 0x0008
Const $ADS_UF_LOCKOUT = 0x0010
Const $ADS_UF_PASSWD_NOTREQD = 0x0020
Const $ADS_UF_PASSWORD_CANT_CHANGE = 0x0040
Const $ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x0080
Const $ADS_UF_DONT_EXPIRE_PASSWD = 0x10000
Const $ADS_UF_SMARTCARD_REQUIRED = 0x40000
Const $ADS_UF_PASSWORD_EXPIRED = 0x800000
Const $ADS_PROPERTY_CLEAR = 1
Const $ADS_NAME_INITTYPE_GC = 3
Const $ADS_NAME_TYPE_NT4 = 3
Const $ADS_NAME_TYPE_1779 = 1
;
$oMyError = ObjEvent("AutoIt.Error", "ComError")
$objRootDSE = ObjGet("LDAP://RootDSE")
$strDNSDomain = $objRootDSE.Get ("defaultNamingContext")
; Use the NameTranslate object to find the NetBIOS domain name from the
; DNS domain name.
$objTrans = ObjCreate("NameTranslate")
$objTrans.Init ($ADS_NAME_INITTYPE_GC, "")
$objTrans.Set ($ADS_NAME_TYPE_1779, $strDNSDomain)
$strNetBIOSDomain = $objTrans.Get ($ADS_NAME_TYPE_NT4)
;' Remove trailing backslash.
$strNetBIOSDomain = StringLeft($strNetBIOSDomain, StringLen($strNetBIOSDomain) - 1)
;' Use the NameTranslate object to convert the NT user name to the
;' Distinguished Name required for the LDAP provider.
$objTrans.Set ($ADS_NAME_TYPE_NT4, $IDomain & "\" & $IUserId)
$strUserDN = $objTrans.Get ($ADS_NAME_TYPE_1779)
;Get User Info
$usr = ObjGet("LDAP://" & $strUserDN)
$usr.employeeID = $IEmpId
$usr.SetInfo

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

  • Developers

Great man!!!

That is all I need!!!

Thanks again.

I just needs to understand how this works... :P (hehehehee)

Pierre

When i started with this stuff i just searched the internet for VBS scripts that more or less did what i wanted and converted those to AutoIt3 Com ..... :lmao:

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

  • 3 months later...

When i started with this stuff i just searched the internet for VBS scripts that more or less did what i wanted and converted those to AutoIt3 Com ..... :think:

Maybe you would be so kind and show me the way how to retreive 'computer names' with AutoIt (ldap). I tried to do something with your codes but it's yet too dificult for me to modify it fully on my own :(

I want to make program that will join computers to domain (and many more) but before it will do so i need to ask domain if 'computer' and variations of it with numbers (like computer1, computer2, computer3) exists. If so then i will try next number :) Many tnx for any help on this issue.

My little company: Evotec (PL version: Evotec)

Link to comment
Share on other sites

  • Developers

Maybe you would be so kind and show me the way how to retreive 'computer names' with AutoIt (ldap). I tried to do something with your codes but it's yet too dificult for me to modify it fully on my own :think:

I want to make program that will join computers to domain (and many more) but before it will do so i need to ask domain if 'computer' and variations of it with numbers (like computer1, computer2, computer3) exists. If so then i will try next number :( Many tnx for any help on this issue.

Needs more testing but think its close:

#include <GUIConstants.au3>
#include <GUIListView.au3>
Global $computerDomain = "dc=your,dc=dom"
Global $computerName = ""
Global $computerDN = ""
; show pc's starting with pca
_Enumcomputers($computerDomain,"pca") 
ConsoleWrite('$computerName = ' & $computerName & @lf)
ConsoleWrite('$computerDN = ' & $computerDN & @lf )
;
Exit


Func _Enumcomputers($IDomain, $l_computerId)
 ; 
    $Found_computers = ""
    $H2_Search = GUICreate("Select Workstation", 700, 500, Default, Default)
    $h_msg = GUICtrlCreateLabel("Searching .... one moment", 5, 5, 200, 40)
    GUICtrlSetColor(-1, 0xff0000)
    GUICtrlSetFont(-1, 10, 800)
    $h_LV = GUICtrlCreateListView("Found Computers| DN ", 5, 35, 680, 400)
    _GUICtrlListViewSetColumnWidth ($h_LV, 0, 120) 
    _GUICtrlListViewSetColumnWidth ($h_LV, 1, 600) 
    $Counter = 0
    GUISetCursor(15, Default, $H2_Search)
    Local $objCommand = ObjCreate("ADODB.Command")
    Local $objConnection = ObjCreate("ADODB.Connection")
    $objConnection.Provider = "ADsDSOObject"
    $objConnection.Open ("Active Directory Provider")
    $objCommand.ActiveConnection = $objConnection
    Local $strBase = "<GC://" & $computerDomain & ">"
    Local $strFilter = "(&(objectCategory=computer)(CN=" & $l_computerId & "*))"
    Local $strAttributes = "cn,distinguishedName"
    Local $strQuery = $strBase & ";" & $strFilter & ";" & $strAttributes & ";subtree"
    $objCommand.CommandText = $strQuery
    $objCommand.Properties ("Page Size") = 100
    $objCommand.Properties ("Timeout") = 30
    $objCommand.Properties ("Cache Results") = False
    $ADS_SCOPE_SUBTREE = 2
    $objCommand.Properties ("searchscope") = $ADS_SCOPE_SUBTREE
    Local $objRecordSet = $objCommand.Execute
    While Not $objRecordSet.EOF
        $strCN = $objRecordSet.Fields ("cn").value
        $strdistinguishedName = $objRecordSet.Fields ("distinguishedName").value
        $Counter = $Counter + 1
        if $Counter = 2 then     GUISetState(@SW_SHOW, $H2_Search)
        If $Counter > 500 Then ExitLoop
        GUICtrlCreateListViewItem($strCN & "|" & $strdistinguishedName, $h_LV)
        $objRecordSet.MoveNext
    WEnd
    $objConnection.Close
    GUISetCursor(2, Default, $H2_Search)
    If $Counter > 500 Then
        GUICtrlSetData($h_msg, "Showing First 500 records. Select computer to process")
    Else
        GUICtrlSetData($h_msg, "Select computer to process")
    EndIf
    GUICtrlSetColor($h_msg, 0x000000)
    $H2_Ok = GUICtrlCreateButton("Ok", 265, 450, 60, 30, $BS_DEFPUSHBUTTON)
    $H2_Cancel = GUICtrlCreateButton("Cancel", 375, 450, 60, 30)
 ; Check if any match is found
    If $Counter = 0 Then
        Return ""
    EndIf
    $MouseDown = 0
 ; If only 1 found than assume it the one wanted
    If $Counter = 1 Then
        GUIDelete($H2_Search)
        $computerName = $strCN
        $computerDN = $strdistinguishedName
        Return $strCN
    EndIf
 ;
    While 1
        $msg = GUIGetMsg($H2_Search)
        If $msg = 0 Then ContinueLoop
        If $msg = $GUI_EVENT_CLOSE Or $msg = $H2_Cancel Then
            GUIDelete($H2_Search)
            Return ""
        EndIf
        If $msg = $H2_Ok Then
         ; retrieve selected computername
            $SelectLine = StringSplit(GUICtrlRead(GUICtrlRead($h_LV)), "|")
            If $SelectLine[0] = 2 Then
                $computerName = $SelectLine[1]
                $computerDN = $SelectLine[2]
                GUIDelete($H2_Search)
                Return $SelectLine[1]
            EndIf
        EndIf
     ; check for Doubleclick
        If $msg = $GUI_EVENT_PRIMARYDOWN Then
            If $MouseDown = 0 Then
                $MouseDown = TimerInit()
            Else
             ; cliked twice within 400 ms thus selected this entry
                If TimerDiff($MouseDown) < 400 Then
                 ; retrieve selected computername
                    $SelectLine = StringSplit(GUICtrlRead(GUICtrlRead($h_LV)), "|")
                    If $SelectLine[0] = 2 Then
                        $computerName = $SelectLine[1]
                        $computerDN = $SelectLine[2]
                        GUIDelete($H2_Search)
                        Return $SelectLine[1]
                    EndIf
                EndIf
            EndIf
        EndIf
     ; Reset count when time between clicks is longer than 400ms
        If $MouseDown > 0 And TimerDiff($MouseDown) > 400 Then $MouseDown = 0
    WEnd
EndFunc;==>_Enumcomputers
Edited by JdeB

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Here's the code i managed to cut out from JDeB code. I added few things but it doesn't seems to work. Now i thought i would like to have more then just computername, but also when it was created and last modified (basically everything what i can get about that 'COMPUTER'. Doesn't seems to work for me too well. For example if there is no description i get '0', but if there is description in domain i get empty string.

#include <GUIConstants.au3>
#include <GUIListView.au3>
Global $computerDomain = "dc=test,dc=ad"
Global $computerName = ""
Global $computerDN = ""
;
_Enumcomputers($computerDomain,"computer_name")
;ConsoleWrite('$computerName = ' & $computerName & @lf)
;ConsoleWrite('$computerDN = ' & $computerDN & @lf )
;
Exit

Func _Enumcomputers($IDomain, $l_computerId)
    Local $objCommand = ObjCreate("ADODB.Command")
    Local $objConnection = ObjCreate("ADODB.Connection")
    $objConnection.Provider = "ADsDSOObject"
    $objConnection.Open ("Active Directory Provider")
    $objCommand.ActiveConnection = $objConnection
    Local $strBase = "<GC://" & $computerDomain & ">"
    Local $strFilter = "(&(objectCategory=computer)(CN=" & $l_computerId & "*))"
    Local $strAttributes = "cn,distinguishedName,description,operatingSystem,sAMAccountname";,modified,created"
    Local $strQuery = $strBase & ";" & $strFilter & ";" & $strAttributes & ";subtree"
    $objCommand.CommandText = $strQuery
    $objCommand.Properties ("Page Size") = 100
    $objCommand.Properties ("Timeout") = 30
    $objCommand.Properties ("Cache Results") = False
    $ADS_SCOPE_SUBTREE = 2
    $objCommand.Properties ("searchscope") = $ADS_SCOPE_SUBTREE
    Local $objRecordSet = $objCommand.Execute
    While Not $objRecordSet.EOF
        $strCN = $objRecordSet.Fields ("cn").value
        $strdistinguishedName = $objRecordSet.Fields ("distinguishedName").value
        $strDescription = $objRecordSet.Fields ("description").value
        $strOperatingSystem = $objRecordSet.Fields ("operatingSystem").value
        $strsAMAccountname = $objRecordSet.Fields ("sAMAccountname").value
       ;$strCreated = $objRecordSet.Fields ("created").value
       ;$strModified = $objRecordSet.Fields ("modified").value
        MsgBox(1,"JdeB The Greatest!", $strCN & @CRLF & $strdistinguishedName & @CRLF & $strdescription & @CRLF & $strOperatingSystem & @CRLF & $strsAMAccountname)
        $objRecordSet.MoveNext
    WEnd
    $objConnection.Close
EndFunc

My little company: Evotec (PL version: Evotec)

Link to comment
Share on other sites

  • Developers

try this version... changes:

- don't use GC but LDAP because not all fields are available at GC level.

- Description for Computer returns Array.

:think:

Func _Enumcomputers($IDomain, $l_computerId)
    Local $objCommand = ObjCreate("ADODB.Command")
    Local $objConnection = ObjCreate("ADODB.Connection")
    $objConnection.Provider = "ADsDSOObject"
    $objConnection.Open ("Active Directory Provider")
    $objCommand.ActiveConnection = $objConnection
    Local $strBase = "<LDAP://" & $computerDomain & ">"
    Local $strFilter = "(&(objectCategory=computer)(Name=" & $l_computerId & "*))"
    Local $strAttributes = "cn,distinguishedName,Description,operatingSystem";,modified,created"
    Local $strQuery = $strBase & ";" & $strFilter & ";" & $strAttributes & ";subtree"
    $objCommand.CommandText = $strQuery
    Local $objRecordSet = $objCommand.Execute
    While Not $objRecordSet.EOF
        $strCN = $objRecordSet.Fields ("cn").value
        $strdistinguishedName = $objRecordSet.Fields ("distinguishedName").value
        $strDesc = $objRecordSet.Fields ("Description").value
        $strDescription = ""
        If IsArray($strDesc) Then
            FOR $desc IN $strDesc
                $strDescription = $strDescription & $desc & @LF
            NEXT
        EndIf
        $strOperatingSystem = $objRecordSet.Fields ("operatingSystem").value
      ;$strCreated = $objRecordSet.Fields ("created").value
      ;$strModified = $objRecordSet.Fields ("modified").value
        ConsoleWrite("CN= " & $strCN & @LF & "DN= " & $strdistinguishedName &  @LF & "Desc= " &  $strdescription &   @LF & "OS= " &  $strOperatingSystem  & @LF & @LF)
        $objRecordSet.MoveNext
    WEnd
    $objConnection.Close
EndFunc

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

  • Developers

How about ?

Func _Enumcomputers($IDomain, $l_computerId)
    Local $objCommand = ObjCreate("ADODB.Command")
    Local $objConnection = ObjCreate("ADODB.Connection")
    $objConnection.Provider = "ADsDSOObject"
    $objConnection.Open ("Active Directory Provider")
    $objCommand.ActiveConnection = $objConnection
    Local $strBase = "<LDAP://" & $computerDomain & ">"
    Local $strFilter = "(&(objectCategory=computer)(Name=" & $l_computerId & "*))"
    Local $strAttributes = "cn,distinguishedName,Description,operatingSystem,whencreated,whenchanged";
    Local $strQuery = $strBase & ";" & $strFilter & ";" & $strAttributes & ";subtree"
    $objCommand.CommandText = $strQuery
    Local $objRecordSet = $objCommand.Execute
    While Not $objRecordSet.EOF
        $strCN = $objRecordSet.Fields ("cn").value
        $strdistinguishedName = $objRecordSet.Fields ("distinguishedName").value
        $strDesc = $objRecordSet.Fields ("Description").value
        $strDescription = ""
        If IsArray($strDesc) Then
            FOR $desc IN $strDesc
                $strDescription = $strDescription & $desc & @LF
            NEXT
        EndIf
        $strOperatingSystem = $objRecordSet.Fields ("operatingSystem").value
        $strCreated = $objRecordSet.Fields ("whencreated").value
        $strModified = $objRecordSet.Fields ("whenchanged").value
        ConsoleWrite("CN= " & $strCN & @LF & "DN= " & $strdistinguishedName &  @LF & "Desc= " &  $strdescription &   @LF & "OS= " &  $strOperatingSystem & "Created= " &  $strCreated  & "Modified= " &  $strModified & @LF & @LF)
        $objRecordSet.MoveNext
    WEnd
    $objConnection.Close
EndFunc
Edited by JdeB

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

  • Developers

Nice :think: Could you gimme some links (if you have with lots of info about domain and ldap commands) so i wouldn't bother you every 5 minutes ;p

I use http://msdn.microsoft.com/ and Google. Just searching for "LDAP VBS Computer" gives you a nice long list with examples...

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Few problems :think: I was playing with the code and it seems that best value for my needs is LastLogon value. Problem is right now it's showing some weird "signs" and not the right value. Any suggestions (i'm thinking it's maybe not a string but integer but i am not 100% sure). I also found .vbs file (attached at the bottom) and i see some values like objLastLogon.HighPart that i don't know what they stand for. The other problem is how to get this code running on computer without domain (since that's what i need it for). Tried RunAsSet but it didn't work. I'm getting error:

Renamer_0.0.1.au3 (187) : ==> Object referenced outside a "With" statement.:

$strCN = $objRecordSet.Fields ("cn").value

$strCN = $objRecordSet.Fields ("cn")^ ERROR

Func _Enumcomputers($IDomain, $l_computerId)
    Local $objCommand = ObjCreate("ADODB.Command")
    Local $objConnection = ObjCreate("ADODB.Connection")
    $objConnection.Provider = "ADsDSOObject"
    $objConnection.Open ("Active Directory Provider")
    $objCommand.ActiveConnection = $objConnection
    Local $strBase = "<LDAP://" & $domain_long & ">"
    Local $strFilter = "(&(objectCategory=computer)(Name=" & $l_computerId & "*))"
    Local $strAttributes = "cn,distinguishedName,Description,operatingSystem,whencreated,whenchanged,LastLogon"; whenChanged, createTimeStamp, sAdsPath, LastLogon, lastLogonTimestamp
    Local $strQuery = $strBase & ";" & $strFilter & ";" & $strAttributes & ";subtree"
    $objCommand.CommandText = $strQuery
    Local $objRecordSet = $objCommand.Execute
    While Not $objRecordSet.EOF
        $strCN = $objRecordSet.Fields ("cn").value
        $strdistinguishedName = $objRecordSet.Fields ("distinguishedName").value
        $strDesc = $objRecordSet.Fields ("Description").value
        $strDescription = ""
        If IsArray($strDesc) Then
            FOR $desc IN $strDesc
                $strDescription = $strDescription & $desc & @LF
            NEXT
        EndIf
        $strOperatingSystem = $objRecordSet.Fields ("operatingSystem").value
        $strCreated = $objRecordSet.Fields ("whencreated").value
        $strModified = $objRecordSet.Fields ("whenchanged").value
        $strLastLogon = $objRecordSet.Fields ("LastLogon").value
        MsgBox(1,1,"CN= " & $strCN & @LF & "DN= " & $strdistinguishedName &  @LF & _
                   "Desc= " &  $strdescription &   @LF & "OS= " &  $strOperatingSystem & @LF & _
                   "Created= " &  $strCreated  & @LF & "Modified= " &  $strModified & @LF & _
                   "LastLogon= " & $strLastLogon & @LF)
        $objRecordSet.MoveNext
    WEnd
    $objConnection.Close
EndFunc

' LastLogon.vbs
' Example VBScript to display when an object last logged on
' Version 2.0 - August 2005
' ---------------------------------------------------------'
Option Explicit
Dim objOU, objUser, objRootDSE, objLastLogon
Dim strContainer, strDNSDomain
Dim intLastLogonTime, intGuyTime
' --------------------------------------------------------'
' Note: Please change OU=Droitwich, to reflect your domain
' --------------------------------------------------------'
strContainer = "OU=Droiwich, "

Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")

strContainer = strContainer & strDNSDomain
set objOU =GetObject("LDAP://" & strContainer )
For Each objUser In objOU
Set objLastLogon = objUser.Get("lastLogon")
intLastLogonTime = objLastLogon.HighPart * (2^32) + objLastLogon.LowPart
intLastLogonTime = intLastLogonTime / (60 * 10000000)
intLastLogonTime = intLastLogonTime / 1440

Wscript.Echo objUser.givenName & " 's last logon time: " _
& intLastLogonTime + #1/1/1601#
Next
WScript.Quit

' End of lastLogon example VBScript

Any help will be appreciated. Tnx :(

My little company: Evotec (PL version: Evotec)

Link to comment
Share on other sites

  • Developers

The other problem is how to get this code running on computer without domain (since that's what i need it for). Tried RunAsSet but it didn't work. I'm getting error:

Before looking at anything else: The script till now was for use with an Active directory DC not local accounts. Your quoted statement implies you want to do something with Local (pc) accounts ? Edited by JdeB

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Well, no. I'm writting a program that will change name of computer, join computers into domain, add user from domain to Local Administrator. Before you do that it will display you a list of computers in domain (so when you will be adding computer to domain you won't replace some other computer that has the same name). I already took some code from this forum (might be yours ;p) and it works fine as for verifing if user is Domain Admin and has rights to do what he needs to do. The function that checks for computers/users in domain could use those credentials. Hope you know what i mean. To summarize:

So what i would like to do is to have ability to run the script on computer that has network connection but isn't connected to domain yet (logged in with local Administrator account). When i start a script SecurityCHeck() asks me for login/password and it checks if the account i type in is in DOmain Admins. If it is GUI starts and i can work with it. IF not Bye Bye. Now i neeed to make the script to use those credentials to gather information with LDAP.

(ignore polish text ;p)

Func SecurityCheck()
    Global $domain_user = InputBox("Security Check", "Enter login" & @CRLF & @CRLF & @CRLF & _
                            "Osobą kontaktowa: MadBoy" & @CRLF & _
                            "Telefon: (0) PhoneNumber", "", "")
    Global $domain_password = InputBox("Security Check", "Enter Password", "", "*")
    If UserValidate($domain_long, $domain_user, $domain_password, $domain_group) = 1 Then
    MsgBox(1,1,"Great :)")
    
    Else
    $i_Res = MsgBox(5 + 16 + 8192, 'Blad 01 - Logowanie nie powiodło się!', 'Sprawdź następujące punkty:' & @LF & @LF & _
                                   ' - Czy wpisałes porawny login?' & @LF & _ 
                                   ' - Czy wpisałes poprawne hasło?' & @LF & _
                                   ' - Czy jestes uprawnionym uzytkownikiem?' & @LF & _
                                   ' - Czy jestes w grupie ' & $domain_group & ' ?' & @LF & @LF & _
                                   'W razie problemów kontaktuj się z MadBoy.' )
            If $i_Res = 4 Then
                SecurityCheck()
            Else
                Exit
            EndIf
    EndIf
EndFunc 

Func UserValidate($domain, $UserName, $Password, $InGroup="")
    Local $NameSpace = ObjGet("WinNT:")
    Local $ADS_SECURE_AUTHENTICATION = 0x0001
    Local $DomObj = $NameSpace.OpenDSObject("WinNT://" & $domain , $UserName, $Password, $ADS_SECURE_AUTHENTICATION)
    If @error <> 0 Then Return 0
    If $InGroup <> "" Then
        $objUser = ObjGet("WinNT://" & $Domain & "/" & $UserName)
        For $oGroup in $objUser.Groups
            If $oGroup.Name = $InGroup Then
                Return 1
            EndIf
        Next
        Return 0
    EndIf
    Return 1
EndFunc

My little company: Evotec (PL version: Evotec)

Link to comment
Share on other sites

  • Developers

I already took some code from this forum (might be yours ;p)

Looks kinda familiar .. :think:

When i start a script SecurityCHeck() asks me for login/password and it checks if the account i type in is in DOmain Admins. If it is GUI starts and i can work with it. IF not Bye Bye. Now i neeed to make the script to use those credentials to gather information with LDAP.

Ok think I understand.

So the script starts under a Local Admin credential.

To be able to verify if the given userId and Password is correct for the AD you could do to following:

- ask for the userid and password.

- do a runasset with the given userid&password and the target Domain.

- runwait the script again but this time with 3 params: "/ADAdmincheck userid password"

- Check at the start of your script for the /ADAdmincheck param and if thats specified, perform the uservalidate function with param 2&3 and return 1 if valid.

- Check the returncode of the runwait and exit if not 1.

something like:

; Check for special tasks 
If $cmdline[0] > 0 Then
    If $cmdline[1] = "/ADAdmincheck" Then
        $rc = UserValidate("yourdomain", $cmdline[1], $cmdline[2], "")
        Exit $rc
    EndIf
EndIf

;Ask Domain Username Password.....
$Domain = "YourDomain"
$UserName = "UID"
$Password = "PSW"
; Rerun this script under the provided credentials to check if part of admin group.
Opt("RunErrorsFatal", 0)
RunAsSet($UserName, $Domain, $Password)
If Not RunWait(@ScriptFullPath & " /ADAdmincheck " & $UserName & " " & $Password) Then Exit
;
;  Rest of script
;
Func UserValidate($Domain, $UserName, $Password, $InGroup = "")
    Local $NameSpace = ObjGet("WinNT:")
    Local $ADS_SECURE_AUTHENTICATION = 0x0001
    Local $DomObj = $NameSpace.OpenDSObject ("WinNT://" & $Domain, $UserName, $Password, $ADS_SECURE_AUTHENTICATION)
    If @error <> 0 Then Return 0
    If $InGroup <> "" Then
        $objUser = ObjGet("WinNT://" & $Domain & "/" & $UserName)
        For $oGroup In $objUser.Groups
            If $oGroup.Name = $InGroup Then
                Return 1
            EndIf
        Next
        Return 0
    EndIf
    Return 1
EndFunc  ;==>UserValidate

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...