使用perl通过adsi接口导出AD帐户列

来源:互联网 发布:淘宝公益宝贝有什么好处 编辑:程序博客网 时间:2024/06/03 19:51
开始是luoluo做的一个vbs脚本,实现从AD导出用户名的功能。脚本方面我偏爱perl,因此用perl重做了一个,顺便修复了luoluo脚本中的一个小bug,加了一行使脚本能够导出1000个以上的账号。

perl脚本很简单,主要注意几点,首先是adsi的属性使用hash表的方式来设置或者获取;另外一个是注意有的属性有点不一样,需要设置hash的hash,例如$objCommand -> Properties -> {"Page Size"} = 1000;这里。假设域为microsoft,完整的代码如下:
代码:
use warnings;
use strict;
use Win32::OLE;

use constant ADS_UF_ACCOUNTDISABLE => 2;
use constant ADS_SCOPE_SUBTREE => 2;

my $objConnection = Win32::OLE->new( "ADODB.Connection" );
my $objCommand = Win32::OLE->new( "ADODB.Command" );

# open ad
$objConnection -> open( "Provider=ADsDSOObject;" );

$objCommand -> = $objConnection;

# search what and how
$objCommand -> = "select userAccountControl,distinguishedName from 'GC://dc=china,dc=microsoft,dc=com' where objectCategory='user'";

# import all users
$objCommand -> Properties -> {"Page Size"} = 1000;
# search all subtree
$objCommand -> Properties -> = ADS_SCOPE_SUBTREE;

my $objRecordSet = Win32::OLE->new( "ADODB.Recordset" );
$objRecordSet = $objCommand->Execute( ) || die "query data from active directory error,exit/n";

while( not $objRecordSet -> eof )
{
 my $intUAC = $objRecordSet -> Fields("userAccountControl") -> value;
 
 # remove diable account
 if( not ( $intUAC & ADS_UF_ACCOUNTDISABLE ) )
 {
 my $longName = $objRecordSet -> Fields("distinguishedName") -> value;

 if( $longName =~ /^CN=([/w/./-/_]+),/ )
 {
 print ."/n";
 }
 }
 
 $objRecordSet -> MoveNext();
}