【问题标题】:I want to run an .exe command from Perl under Windows我想在 Windows 下从 Perl 运行 .exe 命令
【发布时间】:2013-01-25 04:09:21
【问题描述】:

我已经让 Perl 创建了一组用户名 (@ua);现在我需要检查是否每个都存在于 Active Directory 中。我想到的最好方法是在每个用户上运行 dsquery 并确定命令是否以零或非零退出。我写了以下内容:

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=..."

有什么想法吗?

谢谢!

【问题讨论】:

    标签: windows perl cmd


    【解决方案1】:

    正如 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。

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

      【解决方案3】:

      如果要处理输出,请使用open 函数:

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

      或者如果您只想运行命令,请使用system 函数:

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

      【讨论】:

        猜你喜欢
        • 2014-04-06
        • 2020-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-18
        • 1970-01-01
        • 2010-12-25
        • 2011-06-18
        相关资源
        最近更新 更多