2013-01-24 50 views
1

我已经用Perl创建了一组用户名(@ua);现在我需要检查每个Active Directory中是否存在。我认为这样做的最佳方式是对每个用户运行dsquery,并确定该命令是否以零或非零值退出。我写道:我想在Windows下运行Perl下的.exe命令

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

当我跑,我得到的命令行控制台的这个重复列表:

'C:\ WINDOWS \ SYSTEM32 \ dsquery.exe' 不识别为内部或外部命令,可操作程序或批处理文件。

然而,dsquery.exe 是在该位置,因为我可以通过简单地运行它证明:

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

有什么想法?

谢谢!

回答

3

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

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

如果你需要的命令有更深的控制,试试这个模块:Expect

但如果你真的想要对Active Directory执行查询,最好使用特定的CPAN模块,如Net::LDAP

+1

如果他们使用Cygwin版本,ActivePerl和Strawberry Perl将无法运行,Expect只能在Windows上工作:http://search.cpan.org/~rgiersig/Expect-1.21/Expect.pod#___top – Joel

0

如果你想与输出工作,使用open功能:

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

,或者如果你想只运行命令,使用system功能:

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

由于米格尔说,改为使用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  = '[email protected]'; 
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; 

上面应该几乎做到这一点假设你的域命名的类似machine.foo.local与SBS - 如果不是,你需要谷歌周围一点点,看看如何设置的LdapBase 。

相关问题