1

I've already gotten Perl to create an array of usernames (@ua); now I need to check to see if each one exists in Active Directory. The best way I thought of to do this is to run dsquery on each user and determine if the command exits with zero or nonzero. I wrote the following:

foreach(@ua)
{
    $out = `C:\\Windows\\System32\\dsquery.exe user -samid $_`;
}

When I run this, I get a repeated list of this in the command line console:

'C:\Windows\System32\dsquery.exe' is not recognized as an internal or external command, operable program or batch file.

However, dsquery.exe is in that location, as I can prove by simply running it:

C:\verify_users>C:\Windows\System32\dsquery.exe user -samid ...
"CN=...,OU=...,OU=...,OU=...,DC=...,DC=...,DC=..."

Any thoughts?

Thanks!

4

3 回答 3

3

如果需要运行外部命令,可以使用系统命令:

system("C:\\Windows\\System32\\dsquery.exe user -samid $_");

如果您需要更深入地控制命令,请尝试此模块:Expect

但是,如果您真的想对 Active Directory 进行查询,最好使用特定的 CPAN 模块,例如Net::LDAP

于 2013-01-24T14:53:47.500 回答
3

正如 Miguel 所说,请改用 Net::LDAP。

#!/usr/bin/perl
use warnings;
use strict;

use Net::LDAP;

my $tgt_user = shift or die "Usage: fetch_user_details <username>";

my $Server   = 'server.foo.local';
my $User     = 'user@foo.local';
my $Password = 'userpass';
my $LdapBase = 'OU=SBSUsers,OU=Users,OU=MyBusiness,DC=foo,DC=local';
# To AND conditions: "(&(cond1) (cond2))"
my $Filter   = "SAMAccountName=$tgt_user";


# Bind a connection
my $ad = Net::LDAP->new("ldap://$Server")
        or die("Could not connect to LDAP server: $Server");
my $res = $ad->bind( $User, password=>$Password );
if ($res->code) { die("Unable to bind as user $User: ".$res->error); }

# Run the search
# Could have attrs=>'a,b,c' for a search too
$res = $ad->search(base=>$LdapBase, filter=>$Filter);
if ($res->code) { die("Failed to search: ".$res->error); }

# Display results
my $count = $res->count;
print "Found $count matches\n";

for my $entry ($res->entries) {
        $entry->dump;
        # print $entry->get_value('givenname'),"\n";
}

$ad->unbind;
exit;

假设您的域命名类似于带有 SBS 的 machine.foo.local ,以上内容几乎可以做到 - 如果不是,您需要在谷歌上搜索一下以了解如何设置 LdapBase。

于 2013-01-24T18:21:57.990 回答
0

如果要使用输出,请使用以下open功能:

open(N, "C:\\Windows\\System32\\dsquery.exe user -samid $_ |");

或者,如果您只想运行命令,请使用以下system功能:

system("C:\\Windows\\System32\\dsquery.exe user -samid $_");
于 2013-01-24T15:22:20.423 回答