user2007854
user2007854

Reputation: 111

I want to run an .exe command from Perl under Windows

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!

Upvotes: 1

Views: 3776

Answers (3)

Miguel Prz
Miguel Prz

Reputation: 13792

if you need to run an external command, you can use the system command:

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

If you need a deeper control of the command, try this module: Expect

But if you really want to do querys to Active Directory, it's better to use a specific CPAN Module, like Net::LDAP.

Upvotes: 3

Richard Huxton
Richard Huxton

Reputation: 22893

As Miguel says, use Net::LDAP instead.

#!/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;

The above should pretty much do it assuming your domain-naming is something like machine.foo.local with SBS - if not, you'll need to google around a little to see how to set up the LdapBase.

Upvotes: 3

Thyrst
Thyrst

Reputation: 2568

If you want to work with output, use the open function:

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

or if you want to run the command only, use the system function:

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

Upvotes: 0

Related Questions