Skip to content

Instantly share code, notes, and snippets.

@XavierGeerinck
Created January 5, 2016 18:33
Show Gist options
  • Save XavierGeerinck/2717287bf65f04b1e028 to your computer and use it in GitHub Desktop.
Save XavierGeerinck/2717287bf65f04b1e028 to your computer and use it in GitHub Desktop.
Exercise LDAP Query (Active Directory)
# Toon het aantal leden (members) van alle groepen (gebruik een LDAP-query om alle groepen op te sporen)
# Lees de naam in van 1 groep en geef een overzicht van de leden van deze groep
# dsquery: dsquery.exe * -s satan.hogent.be -u "Xavier Geerinck" -p "Xavier Geerinck"
# -filter "(&(objectcategory=group)(member=*))" -scope subtree
#
# De dsquery gaat bij object category zoeken achter groups en zorgen dat deze members heeft
use Win32::OLE;
use Win32::OLE::Const 'Active DS Type Library';
use Win32::OLE::Variant; # Convert ADSI formats to string
# Set default vars
my $rootObject = bind_object('rootDSE');
my $defaultNamingContext = $rootObject->Get('defaultNamingContext');
# Een LDAP query ddd de groepen te vinden
my $con = Win32::OLE->CreateObject('ADODB.Connection');
$con->{Provider} = "ADsDSOObject";
$con->{Properties}->{"User ID"} = "Xavier Geerinck";
$con->{Properties}->{"Password"} = "Xavier Geerinck";
$con->{Properties}->{"Encrypt Password"} = True;
$con->Open();
my $cmd = Win32::OLE->CreateObject('ADODB.Command');
$cmd->{ActiveConnection} = $con;
#$cmd->{CommandText} = "<dn>;filter;attributes;scope";
$cmd->{CommandText} = "<LDAP://satan.hogent.be>;(&(objectcategory=group)(member=*));cn,distinguishedname,member;subtree";
$cmd->{CommandText} = "SELECT cn, distinguishedname, member FROM 'LDAP://satan.hogent.be/$defaultNamingContext' WHERE objectcategory = 'group' AND member = '*'";
$cmd->{Properties}->{"searchscope"} = ADS_SCOPE_SUBTREE;
$cmd->{Properties}->{"Sort on"} = "cn";
# Ga door de resultaten
my $rs = $cmd->Execute();
print Win32::OLE->LastError() if Win32::OLE->LastError();
$rs->MoveFirst();
my $selectedGroup;
while (!$rs->{EOF}) {
my $amountOfMembers = scalar @{$rs->Fields("member")->Value};
print $rs->Fields("cn")->Value, " ($amountOfMembers) : \n";
# Print members
foreach (sort(@{$rs->Fields("member")->Value})) {
my $removeComma = substr($_, 3, length($_));
print substr($removeComma, 0, index($removeComma, ",")), "\n";
}
print "\n";
print "\n";
$rs->MoveNext();
}
$cmd->Close();
$con->Close();
sub bind_object {
my $dn = shift;
my $dso = Win32::OLE->GetObject('LDAP:');
return $dso->OpenDSObject("LDAP://satan.hogent.be/$dn", "Xavier Geerinck", "Xavier Geerinck", ADS_SECURE_AUTHENTICATION);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment