Jump to content
Sign in to follow this  
DavidLago

Executing OpenFiles /Query with @Comspec - What's wrong?

Recommended Posts

DavidLago

It's Weird. I think I don't get it. Why it doesn't work like it is supposed to?

I need to create a Script to monitor one of our fileservers to check how many users and what users opens how many .EXEs at this server.

The DOS command to do that is simple:

openfiles /query /FO table /V /nh | find /I ".exe" > exportx.log

The DOS command typed at it's prompt. The report out is something like that (and exactly what I need AutoIt to run from 30 to 30 minutes):

[text]

SERVER80 3487273 JULIAN Windows 0 Read R:\PWD\PWD_APP\rpc.exe

SERVER80 5644134 WELTON Windows 0 Read R:\SUPORT\Gho11\Gho5.Exe

SERVER80 6251031 DARLEYMX Windows 0 Read R:\DEVELOPMENT\APPS\Applications.S.Winform.exe

SERVER80 6591869 ELCIOVS Windows 0 Read R:\SUPORT\Prog\VC\vcvw.exe

SERVER80 7984711 SANDREO Windows 0 Read R:\SUPORTE\UTILITARIOS\WinStress\WinStress.exe

SERVER80 8399253 BRIANB Windows 0 Read R:\DEVELOPMENT\FONTS\PGCD\APGC.exe

[/text]

Okay, so, as I've used before with other DOS commands, I inserted that command into a @compsec line, But it just won't work. If you read below there, you'll see how many different attempts I tried. No success.

If Not FileExists(@ScriptDir & "\Export") Then
DirCreate(@ScriptDir & "\Export")
EndIf
 
Global $Hour = "_" & @HOUR & "'" & @MIN & "''"
Global $Date = @YEAR & "-" & @MON & "-" & @MDAY
Global $FullDate = $Date & "_" & $Hour
Global $ReportOut = $FullDate & "_" & IniRead("Config.ini", "ReportOut", "ReportOut", "Report")
Global $ReportDir = @ScriptDir & "\Export\"
Global $FilterExt = IniRead("Config.ini", "FilterExt", "FilterExt", "N")
Global $FileExt = '".' & IniRead("Config.ini", "FileExt", "FileExt", "exe" & '"')
Global $FormatOut = IniRead("Config.ini", "FormatOut", "FormatOut", "Table")
 
Global $QueryCommand = "/query " & "/FO " & $FormatOut & " /V " & "/nh "
Global $FindCommand = "| find /I " & $FileExt
Global $ExportCommand = " > " & $ReportOut & ".log"
 
Global $CommandCombo
 
If $FilterExt = "Y" Then
$CommandCombo = $QueryCommand & $FindCommand & $ExportCommand
Else
$CommandCombo = $QueryCommand & $ExportCommand
EndIf
 
;openfiles /query /FO table /V /nh | find /I ".exe" > exportx.log <--- Command to be used:
;/query /FO '& $FormatOut &' /V /nh | find /I "' & $Extension & '" > ' & $ExportFile & '" "'    
;Local $PID = RunAs("adm-user", "DomainX", "P@ssW0rDX", 4, Run(@ComSpec & "/c openfiles /query /FO table /V /nh | find " & $FileExt & " > exportx.log", @ScriptDir), @ScriptDir) ; <--- The entire command. Didn't work
;local $PID = RunAs("adm-user", "DomainX", "P@ssW0rDX", 4, Run(@ComSpec & "/c openfiles " & $CommandCombo & " ", @ScriptDir), @ScriptDir) ; <--- Narrowed down the arguments to a single variable. Didn't work
 
Local $PID = RunAs("adm-user", "DomainX", "P@ssW0rDX", 4, Run(@ComSpec & "/c openfilescommandline.bat", @ScriptDir), @ScriptDir) ; It was created a bat file that works when executed manually, but doesn't when executed through @comspec
 
MsgBox(0, "", $CommandCombo)
Local $pidreal = StdoutRead($PID)
MsgBox(0, "", $pidreal)

FYI, The ini file is as follows:

[FilterExt]
FilterExt = Y
 
[FileExt]
#FileExt = ".exe"
 
[ReportOut]
ReportOut = _Report
 
[FormatOut]
FormatOut = table

Can anyone tell me what is my sin?

Thanks in advance.


Just a server analyst that has never been into programming that much. So, small fish here :)

Share this post


Link to post
Share on other sites
hannes08

Hi HellFrost,

please have a look at the RunAs() section in the helpfile and you will see that it needs the program name and not the return of Run() (which, btw., is the process id and not the program path).

So far for my two pence. :graduated:


Regards,Hannes[spoiler]If you can't convince them, confuse them![/spoiler]

Share this post


Link to post
Share on other sites
DavidLago

Hey Hannes, thanks for replying.

I tried with Run() alone, and it doesn't work as well. And I used RunAs(....Run(...)) with another script sometime ago and it works, I also used RunAs(...(Shellexecute(...)), and it works, but it doesn't run with @comspec... as simple as I could downsize it to test it.

I'm trying another way now. I just discovered _RunDOS, and I'm testing it now. Apparently it doesn't work with the command line itself, but it gave me some hope when I tried like:

$X='openfiles /query /FO table /V /nh | find /I ".exe" > c:\temp\Export.log'

_RunDOS($X)

There's light at the end of the tunnel, I suppose.

What do you think?


Just a server analyst that has never been into programming that much. So, small fish here :)

Share this post


Link to post
Share on other sites
BrewManNH

You shouldn't be nesting the RunAs and Run statements in the same command. Pick one and use that, probably best to use RunAs if you need the credentials.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
DavidLago

Thanks for the advice, Brewman. I'll keep that in mind:

Guys. found a solution. I'm gonna show it to you on my next post.


Just a server analyst that has never been into programming that much. So, small fish here :)

Share this post


Link to post
Share on other sites
DavidLago

Here comes my lifesaver command of the week:

_RunDOS

Let me show you how my script finally worked out (and then I'm going to post it at the script examples for everyone)

#cs  ---------------------------Script Start-------------------------------------
| Author:        DavidLago (Hellfrost)
| Script Function: Reports out a logfile containing openfiles within a (file)server, configured under an ini file
#ce  ----------------------------------------------------------------------------
;---------------------------------------------------------------INCLUDES--------------------------------------------------------------------------------
#include <Process.au3>
#include <GuiConstantsEx.au3>
#include <WindowsConstants.au3>
#include <array.au3>
#include <Date.au3>
;------------------------------------------------------------EXPORT-FOLDER--------------------------------------------------------------------------------
If Not FileExists(@ScriptDir & "\Export") Then
DirCreate(@ScriptDir & "\Export")
EndIf
;------------------------------------------------------------ WHILE LOOP --------------------------------------------------------------------------------
Global $iNow = _NowCalc()
Global $TimeOut = False
While $TimeOut = False
;---------------------------------------------------------VARIABLES-----------------------------------------------------------------------------------
Global $Date = @MON & "-" & @MDAY & "-" & @YEAR
Global $Hour = @HOUR & "'" & @MIN & "''"
Global $FullDate = $Date & "_" & $Hour
Global $ReportDir = @ScriptDir & "\Export\"
;----------------------------------------------------------INI_READ-----------------------------------------------------------------------------------
Global $MailFrom = IniRead("Config.ini", "Mail", "MailFrom", "Script_OpenFiles@AutoITScripting.net")
Global $Mailto = IniRead("Config.ini", "Mail", "Mailto", "")
Global $MailSubj = IniRead("Config.ini", "Mail", "MailSubj", "")
Global $MailBody = IniRead("Config.ini", "Mail", "MailBody", "")
Global $TimeFreq = IniRead("Config.ini", "Time", "Frequency", "60")
Global $TimeDur = IniRead("Config.ini", "Time", "Duration", "24")
Global $ReportOut = $FullDate & "_" & IniRead("Config.ini", "ReportOut", "ReportOut", "Report")
Global $FilterExt = IniRead("Config.ini", "FilterExt", "FilterExt", "N")
Global $FileExt = '"' & IniRead("Config.ini", "FileExt", "FileExt", "exe") & '"'
Global $FormatOut = IniRead("Config.ini", "FormatOut", "FormatOut", "Table")
;-------------------------------------------------------MATH VARIABLES----------------------------------------------------------------------------------
Global $CommandCombo, $CommandFinal, $iDiff, $FreqDurMath
$iTimeFreq = $TimeFreq * 60000 ; Turn to miliseconds
$iTimeDur = $TimeDur ; Turn to minutes
$FreqDurMath = ($TimeDur * 60) / $TimeFreq
;-------------------------------------------------------ERROR-TREATMENT---------------------------------------------------------------------------------
If $iTimeFreq < 900000 Then
MsgBox(4112, "Error", 'The parameter "FREQUENCY" at the config.ini file is set to a number below 15. 15 minutes is the minumum threshold', 5)
$MailBody = 'The Script "' & @ScriptName & '" is reporting the following error: The parameter "FREQUENCY" at the config.ini file is set to a number below 15. ' & @CRLF & '15 minutes is the minumum threshold'
SendMail($MailBody)
Exit
EndIf
If $FreqDurMath < 1 Then
$MailBody = 'The Script "' & @ScriptName & '" The parameters "FREQUENCY" and "DURATION" at the config.ini file is set to a number which prevents it to loop more than once. Do you want to continue?'
SendMail($MailBody)
If MsgBox(4116, "Error", 'The parameters "FREQUENCY" and "DURATION" at the config.ini file is set to a number which prevents it to loop more than once. Do you want to continue?', 10) = 7 Then Exit
EndIf
;----------------------------------------------------------COMMAND BREED I-------------------------------------------------------------------------------
Global $QueryCommand = "/query " & "/FO " & $FormatOut & " /V " & "/nh "
Global $FindCommand = "| find /I " & $FileExt
Global $ExportCommand = " > " & '"' & $ReportDir & $ReportOut & ".log" & '"'
If $FilterExt = "Y" Then
$CommandCombo = $QueryCommand & $FindCommand & $ExportCommand
Else
$CommandCombo = $QueryCommand & $ExportCommand
EndIf
$CommandFinal = "openfiles " & $CommandCombo
;-------------------------------------------------------------OPTIONS-----------------------------------------------------------------------------------
If $FilterExt = "Y" Then
If $FileExt <> "" Then
TrayTip("Message from the " & @ScriptName & " Script: ", 'The command "' & $CommandFinal & '" is running in this server. Options enabled are the following:' & @CRLF & @CRLF & "Filter: " & '"' & $FilterExt & '"' & @CRLF & "Ext/String: " & $FileExt & @CRLF, 1, 1)
Else
TrayTip("Message from the " & @ScriptName & " Script: ", 'The command "' & $CommandFinal & '" is running in this server.', 1, 1)
EndIf
EndIf
;--------MAIN COMMAND-----------------------------------##################
_RunDOS($CommandFinal)
;--------MAIN COMMAND-----------------------------------##################
$iDiff = _DateDiff('h', $iNow, _NowCalc())
Sleep($iTimeFreq) ; <-Frequency
If $iDiff > $iTimeDur Then ; <-- Is time through?
$TimeOut = True
$MailBody = 'The script "' & @ScriptName & '", which was running at the server "' & @ComputerName & '", generated the requested logs successfully. Please, contact your Domain administrator to claim them'
SendMail($MailBody)
EndIf
WEnd ;==> While from line 18
 
;------------------------Function to send e-mail--------------------------------------------------------------------------------------------------------------
Func SendMail($MailBody)
$objEmail = ObjCreate("CDO.Message")
$objEmail.From = $MailFrom
$objEmail.To = $Mailto
$objEmail.Subject = $MailSubj
$objEmail.Textbody = $MailBody
$objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
$objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"mail.domain.net" ;                       <----------------------------------------- Insert your mailserver here
$objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
$objEmail.Configuration.Fields.Update
$objEmail.Send
EndFunc   ;==>SendMail

And the ini file:

#--------------------------------------------------------------------#
#                          Config. ini                            #
#--------------------------------------------------------------------#
#--------------------------------------------------------------------#
#   OPENFILES REPORT:      #
# Reports out a logfile containing openfiles within a server    #
#--------------------------------------------------------------------#
 
[Time]
 
# What frequency? (Minutes [minimum: 15 min) / How long? (Hours [Minimum: 1H)
Frequency = 15
Duration = 1
 
 
 
[FilterExt]
 
# GREP Extension/String? ( Y, N)
FilterExt = Y
 
 
 
[FileExt]
 
# What's the extension or string combo to be matched? (.exe; .doc; .csv; Solidworks; Report, etc. (default: line commented by #)
FileExt = doc
 
 
 
[ReportOut]
 
# LogFile Sufix
ReportOut = Report
 
 
 
[FormatOut]
 
# LogFile Format: CSV or Table. (default: table)
FormatOut = CSV
 
 
 
[Mail]
 
MailFrom = Script_OpenFiles@AutoITScripts.com
Mailto = david@davidlago.info
MailSubj = OpenFiles Alert
MailBody = This message is an alert.

Thanks for everyone that helped me.

Edited by HellFrost

Just a server analyst that has never been into programming that much. So, small fish here :)

Share this post


Link to post
Share on other sites
BrewManNH

Glad it is finally working for you. BTW, _RunDOS is equal to RunWait(@ComSpec & " /C " & <Command to run>, "", @SW_HIDE), nothing more or less than that, you were basically doing the same thing in your script before but you were nesting the RunAs and Run.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

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
Sign in to follow this  

  • Similar Content

    • goodmanjl531
      By goodmanjl531
      Hope someone can help as quotes within quotes is always confusing.  I am creating a silent install of printer software and want to call via runwait comspec line.
      The call within a cmd line is below
      samsung.exe /s /n"Samsung SL-M3220ND" /p"xxx"
      xxx will be stored as a variable  $PrinterIP which would be as example  10.10.10.20    I need to use a variable as i am doign this for a business and need it to be based on the store i install at that has a specific IP range.
       
      I started with the below as 2 possibilities but no luck..
      RunWait(@ComSpec & "/c " & "samsung.exe /s /n""Samsung SL-M3220ND"" /p""" & $PrinterIP ") RunWait(@ComSpec & "/c " & "samsung.exe /s /n'Samsung SL-M3220ND' /p'" & $PrinterIP '") but i cant get it to compile as i have errors on the line..  thanks in advance.
    • 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!
    • FMS
      By FMS
      Hello,
      I've some troubles whit the run command.
      Below u see 2 command's , 1 is working and the other not. (the first isn't working)
      I think the problem is in te space between program and files.Also I've treid every thing i could think of or the helpfiles handed to me.
      (or maybe I din't find the correct answer:))
      I tried so mush that i don't know anymore if it's the space between program files or not.
      Could somebody point me in the right direction?
      Not working:
      Run(@ComSpec & " /c psexec -i \\127.0.0.1 -u username -p pass -h -d /accepteula C:\Program Files\some_prog\Shell.exe" ,"C:\tools", @SW_HIDE) Working :
      Run(@ComSpec & " /c psexec -i \\127.0.0.1 -u username -p pass /accepteula cmd" , "C:\tools" , @SW_HIDE)  
       
       
       
       
       
       
    • FMS
      By FMS
      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  
×