2013-01-24 46 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 。

相關問題