FMS

trying to find a process on a remote computer

12 posts in this topic

#1 ·  Posted (edited)

hello,

I'm trying to make a check if a process is running on a remote PC.
This is what i got this far when I edit a found snippet on this forum.
 

The function _CMDreturn returns the output of the command line command.
In this output I want to scan if there is a line whit "process mspaint was not found".

This I'm trying to do whit StringLeft.
The problem is that I don't get any error's and also don't get a message if it doesn't exist.

Could somebody say to me what I'm doing wrong here?
Or iff there is a better way to do this?

Thanks in advanced.
 

#include <Constants.au3>

$result= _CMDreturn('C:\Tools\Ps\pslist.exe mspaint')
msgbox(0,"Version",$result)


Func _CMDreturn($sCommand) 
    $cmdreturn = ""
    $stream = Run(@ComSpec & " /c " & $sCommand, @SystemDir, @SW_HIDE, $STDOUT_CHILD + $STDIN_CHILD)
    While 1 
        $line = StdoutRead($stream)
        If @error Then ExitLoop
         If StringLeft($line, 32) = "process mspaint was not found on" Then
            msgbox(0,"not found",$line)
         EndIf
        $cmdreturn &= $line
    WEnd
    Return $cmdreturn
EndFunc

 

Edited by FMS

as finishing touch god created the dutch

Share this post


Link to post
Share on other sites



@FMS It looks as though you're looking for a process, not a service. I would do something like this:

$sPC = "."
$oWMI = ObjGet("winmgmts:" & "{impersonationLevel=impersonate}!\\" & $sPC & "\root\cimv2")
$oProcessList = $oWMI.ExecQuery ("Select * from Win32_Process Where Name = 'MSPaint.exe'")

    For $sProcess in $oProcessList
        ConsoleWrite($sProcess.Name & @CRLF)
    Next

 


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Indeed, i was trying to find a process not a service :)
Sorry for the confuson , i edited the question.

Thanks for the better way you are showing.
I'll try make this work. (not shure iff this will work remote :) I'm not known whit $oWMI.ExecQuery
thanks in advanced.

Edited by FMS

as finishing touch god created the dutch

Share this post


Link to post
Share on other sites

Just put in the PC name for the $sPC variable. As long as you can ping the machine (and WMI is not blocked through company policy) you should be able to run that query. If you have a multi-domain environment you may have to put the fully qualified domain name for the PC in (Ex: machinename.mycompany.com).


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

Thanks , i fully tested your code line and works nicly @JLogan3o13

As I mentioned before I'm not known whit WMI but it works.
I think it is time to learn a bit more from WMI :)
As I see now it's less code to do the same.


as finishing touch god created the dutch

Share this post


Link to post
Share on other sites

humm unfortunaly i get an  -2147024891 error :( ( General access denied error (incorrect login).)
At home it was working like a charm but i think the network @work isn't accepting this kind of requests.?

Now i got 2 options:

-changing the login of this service whish i don't think is possible , or
-go to mine original question.

somebody got any ideas on this?
 


as finishing touch god created the dutch

Share this post


Link to post
Share on other sites

If it is an incorrect login, and you know the credentials that will work, just compile your script and then look at RunAs in the help file.


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

Sound great that runas :)
but unfortunaly I need to use the whole programm to use the @username for settings purpouse and
$LC_result_objget = RunAs ( "username", "domain", "pass", 2, ObjGet("winmgmts:" & "{impersonationLevel=impersonate}!\\" & $_IP & "\root\cimv2"))

will not work :)
I was looking into WMI and runas but din't found anythin usefull.
(It can also be that I don't now how to look because WMI is new for me)

At this point I'm leaning more to the @comspec/pslist way, in whish I'm a little bit further. :
(I think this way is a lot slower than the WMI way but i got it to work:S)

$cmdreturn = ""
$process = "mspaint"
$sCommand = "D:\Tools\Ps\pslist.exe " & $process
$stream = Run(@ComSpec & " /c " & $sCommand, @SystemDir, @SW_HIDE, $STDOUT_CHILD + $STDIN_CHILD)
While 1
  $line = StdoutRead($stream)
  If @error Then ExitLoop
  $cmdreturn &= $line
WEnd

$count = 0

$aArray = StringSplit(StringTrimRight(StringStripCR($cmdreturn), StringLen(@CRLF)), @CRLF)

For $i = 0 To UBound($aArray) - 1
  If StringLeft($aArray[$i], 7) = $process Then
    $count += 1
  EndIf
Next

If $count = 0 Then
    msg("found","nothing found")
Else
    If $count = 1 Then
        msg("found","found")
    Else
        msg("found","multiple found count = " & $count)
    EndIf
EndIf

_ArrayDisplay($aArray)

 


as finishing touch god created the dutch

Share this post


Link to post
Share on other sites

I did something similar, but returning an array of all processes with

#include <Array.au3>
;#include <MsgBoxConstants.au3>

$c = InputBox ("Computer", "Enter the computer name for which you want to list the currently running processes and PIDs.")
$c = "\\" & $c
$a = ProcessList ($c)
_ArrayDisplay ($a)

Good luck.


Meds.  They're not just for breakfast anymore. :'(

Share this post


Link to post
Share on other sites

You can use also the built-in tool tasklist.exe.


Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Share this post


Link to post
Share on other sites

in case :

 

Quote
-2147024891 0x80070005  General access denied error (incorrect login).

 

 

; This ErrorHandler is for detect bad credential
Global $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")
Func _ErrFunc()
EndFunc ;==> _ErrFunc

Local $objWMILocator = ObjCreate("WbemScripting.SWbemLocator")
If @error Then Return SetError(1, 0, 0)

Local $objWMI = $objWMILocator.ConnectServer($sComputer, "\\.\root\cimv2", $sUser, $sPass, "", "", $wbemConnectFlagUseMaxWait)
If @error Then Return SetError(2, 0, 0)

Local $colItem = $objWMI.ExecQuery(...

 

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

thanks @UEZ in both cases i ques :) (his own answer and @Synapsee answer :)

stupid of me that i din't think of plain old tasklist :)
for the answer of synapsee , this sees good but i have to try at work if it works :)
as I mentioned before I don't know mush about WMI and is rather new for me.

(I'm not following his answer in the WMI error handling topic)
so iff I'm reading it right I can first connect whit another account before I execute :

$oWMI = ObjGet("winmgmts:" & "{impersonationLevel=impersonate}!\\" & $sPC & "\root\cimv2")

?

Edited by FMS

as finishing touch god created the dutch

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • ModemJunki
      By ModemJunki
      Hello,
      In Windows 10 PowerShell, one can do this to change the metric for a NIC in Windows 10:
      Get-NetAdapter | Where-Object -FilterScript {$_.InterfaceAlias -Eq "Ethernet 2"} | Set-NetIPInterface -InterfaceMetric 2 I know I can script the above PowerShell line (and it works!), but I wanted to try something I hadn't done before after looking into jguinch's most excellent Network configuration UDF. I wanted to make use of the SetIPConnectionMetric method in the WMI classes. There is an example VBscript here but this is not for Windows 10. Using AutoIT would also give better control over capturing error return codes than with PowerShell.
      But I cannot get my script to work! The return from SetIPConnectionMetric() is 0, which would indicate success. Yet the change does not happen. I also tried WMI methods using .put_ but this fails.
      Anyone more experienced than I have ideas to make this work?
      #RequireAdmin _SetNicInterfaceMetric2("Ethernet 2", "2") Func _SetNicInterfaceMetric2($NIC_NAME, $METRIC) Local $s_setIndx = 0 $objWMIService = ObjGet("winmgmts:{impersonationLevel = impersonate}!\\" & "." & "\root\cimv2") $colNICItems = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID = '" & $NIC_NAME & "'", "WQL") If IsObj($colNICItems) Then For $objItem In $colNICItems $s_nicIndex = $objItem.Index Next ConsoleWrite("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = '" & $s_nicIndex & "'" & @CRLF) $colNAC = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = '" & $s_nicIndex & "'", "WQL") If IsObj($colNAC) Then For $objNetCard In $colNAC If $METRIC <> $objNetCard.IPConnectionMetric Then ConsoleWrite("Metric was set to " & $objNetCard.IPConnectionMetric & ". Setting to " & $METRIC & "." & @CRLF) $s_isSet = $objNetCard.SetIPConnectionMetric($METRIC) ConsoleWrite("SetIPConnectionMetric Result = " & $s_isSet & @CRLF) Else ConsoleWrite("Metric is already set to " & $METRIC & @CRLF) EndIf Next EndIf EndIf EndFunc ;==>_SetNicInterfaceMetric2  
    • AndyS19
      By AndyS19
      I have code that does a WMI SQL query to find all defined printers, and I want to parse the returned object in several places.  However, after parsing it the first time, all other times fail to find any printer objects.
      Here is my test code:
      test() Func test() Local $oPrinters, $oPrinter, $err, $cnt, $oP, $query $query = "SELECT * FROM Win32_Printer" $oPrinters = doQuery($query) $err = @error LogMsg("+++: $err = " & $err & ", isObj($oPrinters) = " & IsObj($oPrinters)) If ($err == 0) Then LogMsg("FIRST LOOP") ; <=== FIRST LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") LogMsg("SECOND LOOP") ; <== SECOND LOOP $cnt = 0 $oP = $oPrinters LogMsg("+++: isObj($oP) = " & IsObj($oP)) For $oPrinter In $oP $cnt += 1 LogMsg("+++: isObj($oPrinter): " & IsObj($oPrinter) & ", $oPrinter.Name ==>" & $oPrinter.Name & "<==") Next LogMsg("+++: Found " & $cnt & " printers") EndIf EndFunc ;==>test Func doQuery($sQuery, $lnum = @ScriptLineNumber) #forceref $lnum LogMsg("+++:" & $lnum & ": doQuery(" & '"' & $sQuery & '"' & ") entered") Local $oWMIService, $oResults, $errstr Local $wbemFlags = BitOR(0x20, 0x10) ; $wbemFlagReturnImmediately and wbemFlagForwardOnly $oWMIService = ObjGet("winmgmts:\\" & "localhost" & "\root\CIMV2") If (IsObj($oWMIService)) Then $oResults = $oWMIService.ExecQuery($sQuery, "WQL", $wbemFlags) If (IsObj($oResults)) Then LogMsg("+++: doQuery() returns @error = 0, Good: returning the object") Return (SetError(0, 0, $oResults)) ;;; Good: return the object Else $errstr = "" _ & "WMI Query failed." & @CRLF _ & "This is the query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") LogMsg("+++: doQuery() returns @error = 1") Return (SetError(1, 0, $errstr)) ; Error: Query faled EndIf Else $errstr = "" _ & "WMI Output" & @CRLF _ & "No WMI Objects Found for class: " & @CRLF _ & "Win32_PrinterDriver" & @CRLF _ & "using this query:" & @CRLF _ & " " & $sQuery LogMsg("+++: ====>" & $errstr & "<===") MsgBox(0, "ERROR", $errstr) ; Error: Cannot get $oWMIService object Exit (1) EndIf EndFunc ;==>doQuery Func LogMsg($msg, $lnum = @ScriptLineNumber) ConsoleWrite("+++:" & $lnum & ": " & $msg & @CRLF) EndFunc ;==>LogMsg Parsing the returned $oPrinters object shows 5 printers:
      +++:15: FIRST LOOP +++:18: +++: isObj($oP) = 1 +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft XPS Document Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Microsoft Office Document Image Writer<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Fax<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG7100 series Printer WS<== +++:22: +++: isObj($oPrinter): 1, $oPrinter.Name ==>Canon MG6100 series Printer WS<== +++:24: +++: Found 5 printers Parsing it again, shows no printers:
      +++:26: SECOND LOOP +++:29: +++: isObj($oP) = 1 +++:35: +++: Found 0 printers  
    • jguinch
      By jguinch
      Hello.
      I did create these few functions several months ago. I post here, if it can interest someone.
      These functions based on WMI queries allow you to manage printers : add / delete printer, driver, port, or obtain configuration, set default printer ... I let you discover it with the code.

       
      Here is the list of the available functions :
      _Printmgr_AddLocalPort
      _Printmgr_AddLPRPort
      _PrintMgr_AddPrinter
      _PrintMgr_AddPrinterDriver
      _PrintMgr_AddTCPIPPrinterPort
      _PrintMgr_AddWindowsPrinterConnection
      _PrintMgr_CancelAllJobs
      _Printmgr_EnumPorts
      _PrintMgr_EnumPrinter
      _PrintMgr_EnumPrinterConfiguration
      _PrintMgr_EnumPrinterDriver
      _PrintMgr_EnumPrinterProperties
      _PrintMgr_EnumTCPIPPrinterPort
      _Printmgr_Pause
      _Printmgr_PortExists
      _Printmgr_PrinterExists
      _Printmgr_PrinterSetComment
      _Printmgr_PrinterSetDriver
      _Printmgr_PrinterSetPort
      _Printmgr_PrinterShare
      _Printmgr_PrintTestPage
      _PrintMgr_RemoveLocalPort
      _PrintMgr_RemoveLPRPort
      _PrintMgr_RemovePrinter
      _PrintMgr_RemovePrinterDriver
      _PrintMgr_RemoveTCPIPPrinterPort
      _PrintMgr_RenamePrinter
      _Printmgr_Resume
      _PrintMgr_SetDefaultPrinter
       
      And some examples :
      #Include "PrintMgr.au3" ; Remove a printer called "My old Lexmark printer" : _PrintMgr_RemovePrinter("My old Lexmark printer") ; Remove the driver called "Lexmark T640" : _PrintMgr_RemovePrinterDriver("Lexmark T640") ; Remove the TCP/IP printer port called "TCP/IP" _PrintMgr_RemoveTCPIPPrinterPort("MyOLDPrinterPort") ; Add a driver, called "Samsung ML-451x 501x Series", and driver inf file is ".\Samsung5010\sse2m.inf" _PrintMgr_AddPrinterDriver("Samsung ML-451x 501x Series", "Windows NT x86", @scriptDir & "\Samsung5010", @scriptDir & "\Samsung5010\sse2m.inf") ; Add a TCP/IP printer port, called "MyTCPIPPrinterPort", with IPAddress = 192.168.1.10 and Port = 9100 _PrintMgr_AddTCPIPPrinterPort("MyTCPIPPrinterPort", "192.168.1.10", 9100) ; Add a printer, give it the name "My Printer", use the driver called "Samsung ML-451x 501x Series" and the port called "MyTCPIPPrinterPort" _PrintMgr_AddPrinter("My Printer", "Samsung ML-451x 501x Series", "MyTCPIPPrinterPort") ; Set the printer called "My Printer" as default printer _PrintMgr_SetDefaultPrinter("My Printer") ; Connect to the shared printer "\\192.168.1.1\HPDeskjetColor") _PrintMgr_AddWindowsPrinterConnection("\\192.168.1.1\HPDeskjetColor") ; List all installed printers #Include <Array.au3> $aPrinterList = _PrintMgr_EnumPrinter() _ArrayDisplay($aPrinterList) ; List all printers configuration #Include <Array.au3> $aPrinterConfig = _PrintMgr_EnumPrinterConfiguration() _ArrayDisplay($aPrinterConfig) ; List all installed printer drivers #Include <Array.au3> $aDriverList = _EnumPrinterDriver() _ArrayDisplay($aDriverList) ; Retrieve the printer configuration for the printer called "Lexmark T640" #Include <Array.au3> $aPrinterConfig = _PrintMgr_EnumPrinterConfiguration("Lexmark T640") _ArrayDisplay($aPrinterConfig) ; Add a local printer port (for a file output) _AddLocalPrinterPort("c:\temp\output.pcl") ; Remove the local port _RemoveLocalPrinterPort("c:\temp\output.pcl") Download link :  PrintMgr.au3
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning AutoIt community!
      Today, I'm here to ask you if you know how to run an .exe from cmd.exe ( Command Prompt )...
      My intention is to read a .ini file where I store an information that has to be included in the shell, and run an .exe with that information...
      I'll give you an example
      Local $aFileCartellaAuditCopy = _FileListToArray($sPercorsoAuditCopy, "*.txt") If @error Then MsgBox($MB_ICONERROR, "Errore!", "Errore durante la lettura della lista dei file nella directory" & @CRLF & $sPercorsoAuditCopy & @CRLF & "Errore: " & @error) Return False Else Local $iPID = Run("cmd.exe" & ' /k "C:\Users\Portatile-60\Desktop\HmiCheckLogIntegrity.exe" "C:\Users\Portatile-60\Desktop\AuditTrailDosaggio0_20170327_151335_DOSAGGIO_PW_01.txt"') ; & " /k " & '"' & $sHmiCheckLogIntegrity & '"' & " " & '"' & $sPercorsoAuditCopy & "\" & $aFileCartellaAuditCopy[1] & '"', "", @SW_SHOW, $STDOUT_CHILD) Return True EndIf This code is in a function, that returns False if it can retrive at least a file from the path stored in the .ini file...
      Else
      I would like to run the Command Prompt with the .exe and with a parameter of that .exe, but it seems to not work properly.

      Could please anyone tell me why?

      Thanks  
    • WoodGrain
      By WoodGrain
      Hi guys,
      This is probably an obvious one, but I really don't use this command at all so am hoping you can spot my mistake.
      I'm running a powershell script on a schedule with the following script in a function, the function is being called in a loop, but the console process is not closing in the background and I end up with a bunch of console windows running in the background:
      Run(@comspec & ' /k PowerShell.exe -STA -NonInteractive -ExecutionPolicy ByPass -Command "& ''Z:\Powershell\365\GetNextDetails.ps1'' "', "", @SW_HIDE) Thanks!