Jump to content

Run WMIC command in elevated previlage


Recommended Posts

@TheXman Thanks for  the effort mate..

above code gives me message box like "Elevated = True",  but does not give any output from _GetDOSOutput function, tried with normal command ipconfig which is not required elevated permission. still no message .. message is suppressed? or not even executing GetDOSOutput.

 

Link to comment
Share on other sites

Actually that's good.  If you got the MsgBox saying Elevated = True, then the script successfully elevated itself to run with the full admin token.  Everything that is executed in the script after that will run with elevated privileges too. 

Link to comment
Share on other sites

That's because the output from the command was never displayed.  Try this:

Of course I am assuming that your getdos command works.  :)

 

#include <Constants.au3>
#include <WinAPI.au3>


elevate_to_run_with_admin_token()

$sOutput = _GetDOSOutput("wmic /namespace:\\root\dcim\sysman path dcim_biosenumeration where(attributename like '%%Microphone%%') get currentvalue")

MsgBox(0,"Output",$sOutput)


;==========================================================================
; This assumes that the user is a local admin.
; Do NOT use #RequireAdmin if using this method of elevation
;==========================================================================
Func elevate_to_run_with_admin_token()

    Local $sErrorMsg = ""
    Local $iPid      = 0


    ;Run with "runas" verb in order request full Admin token (in Windows Vista and Higher - UAC-enabled OSes).
    If (Not IsAdmin()) And (Not StringRegExp(@OSVersion, "_(?:XP|2000|2003))")) Then
        $iPid = ShellExecute(@AutoItExe, $CmdLineRaw, @ScriptDir, "runas")
        If $iPid Then
            Exit
        Else
            $sErrorMsg = "ERROR: Unable to elevate to Admin due to UAC. " & _WinAPI_GetLastErrorMessage()
            MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", $sErrorMsg)
            Exit -1
        EndIf
    EndIf

    MsgBox( _
        $MB_ICONINFORMATION + $MB_TOPMOST, _
        "INFO", _
        StringFormat("Elevated status = %s", (IsAdmin())?("TRUE"):("FALSE")) _
    )

    Return

EndFunc

Func _GetDOSOutput($sCommand)
    Local $iPID, $sOutput = ""
    $iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
    While 1
        $sOutput &= StdoutRead($iPID, False, False)
        If @error Then
            ExitLoop
        EndIf
        Sleep(10)
    WEnd
    Return $sOutput
EndFunc   ;==>_GetDOSOutput

 

Edited by TheXman
Link to comment
Share on other sites

I just noticed that you used %%Microphone%%.  Change to just %Microphone%.  %% is when you are running it from a command console and need to escape the %.

Link to comment
Share on other sites

Consolewrite will not work because elevation starts a separate process. Either write the ouput to a file, use msgbox,  debugout or some other method to display the output.

Edited by TheXman
Link to comment
Share on other sites

Although this doesn't require elevation, it works for me.  Also, changed Run() to use $STDERR_MERGED.  That way you will see the WMIC error message, if one exists.

 

 

#include <Constants.au3>
#include <WinAPI.au3>


elevate_to_run_with_admin_token()

$sOutput = _GetDOSOutput("wmic csproduct get /format:list")
MsgBox(0,"Output",$sOutput)

$sOutput = _GetDOSOutput("wmic /namespace:\\root\dcim\sysman path dcim_biosenumeration where(attributename like '%Microphone%') get currentvalue")
MsgBox(0,"Output",$sOutput)


;==========================================================================
; This assumes that the user is a local admin.
; Do NOT use #RequireAdmin if using this method of elevation
;==========================================================================
Func elevate_to_run_with_admin_token()

    Local $sErrorMsg = ""
    Local $iPid      = 0


    ;Run with "runas" verb in order request full Admin token (in Windows Vista and Higher - UAC-enabled OSes).
    If (Not IsAdmin()) And (Not StringRegExp(@OSVersion, "_(?:XP|2000|2003))")) Then
        $iPid = ShellExecute(@AutoItExe, $CmdLineRaw, @ScriptDir, "runas")
        If $iPid Then
            Exit
        Else
            $sErrorMsg = "ERROR: Unable to elevate to Admin due to UAC. " & _WinAPI_GetLastErrorMessage()
            MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", $sErrorMsg)
            Exit -1
        EndIf
    EndIf

    MsgBox( _
        $MB_ICONINFORMATION + $MB_TOPMOST, _
        "INFO", _
        StringFormat("Elevated status = %s", (IsAdmin())?("TRUE"):("FALSE")) _
    )

    Return

EndFunc

Func _GetDOSOutput($sCommand)
    Local $iPID, $sOutput = ""
    $iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, $STDERR_MERGED) ; <-- changed to $STDERR_MERGED
    While 1
        $sOutput &= StdoutRead($iPID, False, False)
        If @error Then
            ExitLoop
        EndIf
        Sleep(10)
    WEnd
    Return $sOutput
EndFunc   ;==>_GetDOSOutput

 

Edited by TheXman
Updated to example
Link to comment
Share on other sites

I updated the snippet above.  You weren't capturing the StdErr correctly.  Now you will see the WMIC error messages, if they exist.

Link to comment
Share on other sites

@TheXman

I shall confirm observation with this in an hour ,  Got the output from in the message box as i expected.

Problem = I kept UAC account settings to lower level to do execution now, as mentioned in the previous thread.  i would need to do that settings back and check the observation.  will keep you posted

Link to comment
Share on other sites

Can you tell us what information you're expecting from the output?  You might be able to obtain the same information without using wmi, recently I had to package an app that required audio information, playback and microphone device information so it could be stored in an xml file,  Not sure if that information will help.

 

Link to comment
Share on other sites

@TheXman 

i get UAC POP up with all the other 3 higher UAC level,

i need to keep UAC to lower level Never notify to run this script, 

at last i will do one more check.  i will try to select UAC ok button by UI automtion.  how it sounds?

Link to comment
Share on other sites

I figured that it would trigger UAC since it basically did the same as running with the #RequireAdmin directive.

4 minutes ago, PramodR said:

i will try to select UAC ok button by UI automtion.  how it sounds?

I don't think the script will continue to run while the UAC prompt is waiting unless you spawned another script to actually do the clicking of the button.

If the main goal is to be able to run without prompting, and your users are already local admins, it just seems easier to modify the one registry setting to automatically elevate for admins without prompting.  It's a one-time modification for each workstation.  If you plan on being able to run additional scripts that require elevation in the future, then it seems like the best solution.

Good luck.

:)

 

Link to comment
Share on other sites

 

Hope you mean below settings.

Navigate to the following path using the sidebar folder structure: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

ConsentPromptBehaviorAdmin

0: A value of 0 allows administrators to perform operations that require elevation without consent (meaning prompts) or credentials (meaning authentication).

Note:- This Registry is basically keeping your UI UAC settings to lower, means when you change from UAC UI also this registry will get changed to 0.

@TheXman Thanks for All your suggestions.

Edited by PramodR
Link to comment
Share on other sites

@Everyone 

However i could not elevate powershell window automatically but I am able to solve this problem by reducing only  security level for specific WMI Class.

By manual you can navigate to wmimgmt.msc and add your user..

if you have to add by automation use script available in the below link, after this you no longer needs to elevate power shell console.

https://live.paloaltonetworks.com/t5/Management-Articles/PowerShell-Script-for-setting-WMI-Permissions-for-User-ID/ta-p/53646

 

Thanks everyone for your effort.

 Regards

Pramod R

 

Link to comment
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
 Share

×
×
  • Create New...