I can't get proper Name&Domain properties using Win32_Process::GetOwner call under Perl - perl

I want to enumerate all running processes' name&domain propeties using Win32_Process::GetOwner method under Perl, my code was listed below:
use strict;
use warnings;
use Win32::OLE('in');
use Win32::OLE::Variant;
my $retval;
my $machine = ".";
my $outParam;
my $CLASS = "Winmgmts:{impersonationlevel=impersonate}!\\\\$machine\\root\\cimv2";
my $WMI = Win32::OLE->GetObject($CLASS) or die("GetObject:" . Win32::OLE->LastError());
my $process = $WMI->InstancesOf("Win32_Process");
my $vtName = Win32::OLE::Variant->new(VT_CY, VT_EMPTY);
my $vtDomain = Win32::OLE::Variant->new(VT_CY, VT_EMPTY);
foreach my $obj(in $process)
{
$retval = $obj->GetOwner($vtName, $vtDomain);
if($retval == 0){
print $vtName->Value() . "\t" . $vtDomain->Value() . "\n";
}
}
The script can run properly, but I got the "zero" echo string everytime:
Who can tell me what caused this problem and how to fix it?
Thank you!

Seems Karthik already has the code you're looking for:
my $objWMIService = Win32::OLE->GetObject("winmgmts:\\\\localhost\\root\\CIMV2");
my $sqry = "SELECT * FROM Win32_Process where Name = \"$processName\" ";`
Also seems someone else has the same issue where Perl issues a status code of 0 instead of the actual data:
http://code.activestate.com/lists/perl-win32-users/16230/

Related

perl LDAP entry not recognised

We are writing a Perl code (to be run from Unix) which will reset the password of a Windows AD User. (We are not using powershell as we have been asked not to use Windows scripts).
With the following Perl code, we are able to connect to the AD User directory and query the correct user.
#!/usr/bin/perl -w
#########################
#This script resets the password in active user directory
#########################
use strict;
use warnings;
use DBI;
use Net::LDAP;
use Net::LDAPS;
use Authen::SASL qw(Perl);
use Net::LDAP::Control::Paged;
use Time::Local;
my $CERTDIR = "<cert path>";
my $AD_PASS = "$CERTDIR/.VDIAD_pass";
my $sAN = "vahmed";
### Generate Random Password ###
my $randompass = askPasswd();
my $uninewpass;
my $mail;
my $fullname;
my $name;
my $distName;
my $finalresult;
my #AD_passwords = get_domain_pass();
my $result = reset_AD_Password();
#Reset AD user password
sub reset_AD_Password {
my $ad = Net::LDAP->new($AD_passwords[0]);
my $msg = $ad->bind(dn => "cn=$AD_passwords[2],$AD_passwords[1]",
password => $AD_passwords[3],
version => 3);
if ($msg->code)
{
print "Error :" . $msg->error() . "\n";
exit 2;
}
my $acc_name = 'sAMAccountName';
my $acc_fullname = 'displayName';
my $acc_base = 'manager';
my $acc_distName = 'distinguishedName';
my $acc_mail = 'mail';
my $act = $ad->search(
base => "$AD_passwords[1]",
filter => "(&(objectCategory=person)(sAMAccountName=$sAN))",
attrs => [$acc_name, $acc_fullname, $acc_distName, $acc_mail]);
die 1 if ($act->count() !=1 );
my $samdn = $act->entry(0)->dn;
$fullname = $samdn->get_value($acc_fullname);
$mail = $samdn->get_value($acc_mail);
}
}
However we get an error on the line:
$fullname = $samdn->get_value($acc_fullname);
$mail = $samdn->get_value($acc_mail);
The error states "Can't locate object method "get_value" via package (distinguished Name) (perhaps you forgot to load (distinguished Name))"
However the code works correctly when we replace $samdn with the following code:
foreach my $entry ($act->entries){
$name = $entry->get_value($acc_name);
$fullname = $entry->get_value($acc_fullname);
$distName = $entry->get_value($acc_distName);
$mail = $entry->get_value($acc_mail);
}
It would appear that the code is unable to identify $samdn as a Net::LDAP::Entry record.
We have tried typecasting $samdn but got the same error.
Could someone help in resolving this issue as we would not prefer to use the for loop just in case more that one record is returned by the search? Thanks in advance.
You are not assigning a Net::LDAP::Entry to $samdn. You are assigning the dn of the first entry.
# VVVV
my $samdn = $act->entry(0)->dn;
Get rid of that ->dn and it should work, if $act->entry(0) returns a Net::LDAP::Entry.

How to find a process of the current user in Perl using WMI

Scenario: I want to check if a given process is running, and if so then wait for it to close.
My Perl script is using WMI-->Win32_Process to get the list of running process. I am able to find the running process with the below code
my $objWMIService = Win32::OLE->GetObject("winmgmts:\\\\localhost\\root\\CIMV2");
my $sqry = "SELECT * FROM Win32_Process where Name = \"$processName\" ";`
where $processName is set in the script.
The above code works fine on desktops but the code works in a different way in terminal servers because it the above code pick's up other user's running process.
Question: How can I add a username/id filter in the above query? Is there any easy way to get the process for current user?
Got the solution (workaround at least)..in case any one is interested..
use Win32::OLE::Variant;
my $useridval;
my ($strUser, $strDomain) = ( Variant(VT_BSTR|VT_BYREF, '<undef>'), Variant(VT_BSTR|VT_BYREF, '<undef>') );
foreach my $objItem (in $colItems) {
$useridval = $objItem->GetOwner($strUser, $strDomain);
if (length($useridval) > 0) {
if ($useridval == 0 ){
print ("Process " . $objItem->{Name} . " id: " . $objItem->{ProcessId} . " session id: " . $objItem->{SessionId}) . " owner: " . $strUser->Value . "\n";
}
}
}
Edit: added modified code as the simple variable didn't work. I've removed all error checking to keep it simple
thank you all

Perl NetSNMP extension with multiple devices

I have got a machine (Debian based) with some temperature sensors attached to it, and i would like to query them over snmp, from one script. I can work with one sensor ok, but i am struggling when i plug another one in.
What I am trying to do is loop through each device, and give each one an id, then use this ID as part of the OID, then give it a value.
I've never worked with snmp before, and my perl is not great so any help would be much appreciated. Below is my code:
#!/usr/bin/perl
use NetSNMP::agent (':all');
use NetSNMP::ASN qw(ASN_OCTET_STR ASN_INTEGER);
$BASE_OID=".1.3.6.1.4.1.41050";
$dev_id=1;
$string_value;
$integer_value;
sub pimon_handler {
my ($handler, $registration_info, $request_info, $requests) = #_;
my $request;
my $oid_key;
for($request = $requests; $request; $request = $request->next()) {
$oid_key=$BASE_OID . '.' . $dev_id;
my $oid = $request->getOID();
if ($request_info->getMode() == MODE_GET) {
if ($oid == new NetSNMP::OID($oid_key . '.0')) {
$request->setValue(ASN_OCTET_STR, $string_value);
}
elsif ($oid == new NetSNMP::OID($oid_key . '.1')) {
$request->setValue(ASN_INTEGER, $integer_value);
}
} elsif ($request_info->getMode() == MODE_GETNEXT) {
if ($oid == new NetSNMP::OID($oid_key . '.0')) {
$request->setOID($oid_key . '.1');
$request->setValue(ASN_INTEGER, $integer_value);
}
elsif ($oid < new NetSNMP::OID($oid_key . '.0')) {
$request->setOID($oid_key . '.0');
$request->setValue(ASN_OCTET_STR, $string_value);
}
}
}
}
#location of where we are going to find the 1wire devices
#sensors = `cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slaves`;
chomp(#sensors);
#loop through the sensors we find
foreach $line(#sensors) {
#work out the temp we have got. Need to change this for other sensor types
$output = `cat /sys/bus/w1/devices/$line/w1_slave`;
$output =~ /t=(?<temp>\d+)/;
$integer_value = sprintf "%.0f",$+{temp} / 1000;
$string_value = $line;
my $agent = new NetSNMP::agent();
$agent->register("Pimon$looptest", $BASE_OID . '.' . $dev_id,
\&pimon_handler);
print "Dev $dev_id temp $line temp is $integer_value\n";
$dev_id ++;
}
Are you getting any errors or output?
I suspect that your problem lies in and around your reading the data file by shelling-out to cat instead of opening the file and looping over the linewise contents.
Try dumping the value of #sensors. if it is a single entry array, with the only element containing your entire file, then simply switch #sensors to be scalar. then split $sensors into an array and loop over that.
my $sensors = `read something`
chomp $sensors;
my #sensors = split(/\n/, $sensors);
foreach $line (#sensors) {
...

Passing variables into sqlplus query in perl

I'm having an issue here. I am trying to pass a variable into a sqlplus query, and it does not seem to be working.
my $connect = DBI->connect('DBI:Oracle:',$dbuser,$dbpasswd);
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle='?'", $cycle;
my $query_handle = $connect->prepare($query);
$query_handle->execute();
$cmte_money = $query_handle->fetchrow_array();
print 'Money: ';
print $cmte_money;
if($cmte_money > 0)
{
print 'HI';
}
else
{
print 'NOOOO';
}
I can get the query to work when I change the "cycles" variable from a variable to a constant, and the if statement checking will print hi, so the databases work I'm positive.
I've scoured the internet, and I can't seem to find an answer.
First, you mean to use a placeholder but you don't.
where cycle='?' -- This is a string
should be
where cycle=? -- This is a placeholder
And then there's problem that you don't actually pass a value for the placeholder.
$query_handle->execute();
should be
$query_handle->execute($cycle);
The replacements for placeholders get passed to execute, so:
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle=?";
my $query_handle = $connect->prepare($query);
$query_handle->execute($cycle);
The code you had would have triggered warnings if you had them enabled; make sure you do and that you figure out how to respond to any you get.
Here is an example:
use strict;
use DBI;
my $connect = DBI->connect('DBI:Oracle:', $dbuser, $dbpasswd);
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle = `$cycle`";
my $query_handle = $connect->prepare($query);
$query_handle->execute();
#cmte_money = $query_handle->fetchrow_array();
print 'Money: ';
print #cmte_money;
if($#cmte_money >= 0)
{
print 'HI';
}
else
{
print 'NOOOO';
}
I define a constant variable $cycle, I think like this.
my $connect = DBI->connect('DBI:Oracle:',$dbuser,$dbpasswd);
# Tell the DBI that the query uses bind variable with ? (question mark)
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle=?";
my $query_handle = $connect->prepare($query);
# Pass the value
$query_handle->execute($cycle); # assuming the variable is defined (otherwise it will pass as NULL into the query)
$cmte_money = $query_handle->fetchrow_array();
print 'Money: ';
print $cmte_money;
if($cmte_money > 0)
{
print 'HI';
}
else
{
print 'NOOOO';
}

Mojolicious wildcard placeholders and question mark

The wildcard placeholder (*) is said to match absolutely everything.
But I'm afraid that it doesn't...
I have a webservice with the following method:
get '/*param' => sub {
my $self = shift;
my $param = $self->stash('param');
$self->app->log->debug($param);
}
When i query my service with: http://localhost:3000/search
then the method logs "search" which is ok
but
when i query my service with: http://localhost:3000/search?page=1
then the method also logs "search" which is not ok IMO
I also tried replacing
get '/*param' => sub {
with
get '/:param' => [param => qr/.*/] => sub {
but the result is the same.
Does anybody know of a way around this?
Or should I file this as a bug?
Regards,
Lorenzo
UPDATE
for people with the same problem, I've worked around this issue like this:
get '/*path' => sub {
my $self = shift;
my $path = $self->stash('path');
my #params = $self->param;
if (scalar #params > 0) {
$path .= '?';
foreach my $param (#params) {
$path .= $param . '=' . $self->param($param) . '&';
}
$path = substr($path, 0, length($path) - 1);
}
$self->app->log->debug($path);
}
?page= its not url.
Its param.
So no any bugs here.
you have 'search' in $param.
And $page=1 in stash.
I think Korjavin is right, that's expected behavior. Looks like "page=1" as a parameter and should be in $stash->param('page'). See GET-POST-parameters in ::Lite
If it does not work, maybe renaming the "param" placeholder to something else helps? Maybe it's a name-clash.
The request parameters wouldn't be in the stash.
They're in
$self->req->params
So
my $params = $self->req->params->to_hash;
$self->app->log->debug(Dumper $params);
Should allow you to see the information you're after