Jump to content

check if any process run as administrator


Recommended Posts

hello autoit team
is there any wey to check if any process run as admin or no?
i mean e.g if i want to restart any process, now i have the ability to get the process path and commands line
what i need is a wey to check if the process was runing as admin or no to restart it with the same state.
here is the part that am using it to restart the process

func _processRestart($i_pid, $s_ProcessPath)
if not (ProcessExists($i_ProcessPid)) then return SetError(1, 0, -1)
local $s_ProcessWorkDir = _WinAPI_GetProcessWorkingDirectory($i_ProcessPid)
ProcessClose($i_ProcessPid)
ProcessWaitClose($i_ProcessPid)
ProcessWait(ShellExecute($i_pid,"", $s_ProcessWorkDir))
ProcessesGetList()
return true
endFunc

thanks in advance

Link to post
Share on other sites
  • Developers

Do you want to know whether the User running the process has Admin rights or do you want to know whether the process is running elevated (_WinAPI_IsElevated())?  

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites

@Jos

thanks for the speed on answer

am asking about the externel process, e.g check if notepad.exe is runing as admin

inedition to if the user is admin to ask it to enter the password if it isn't admin

thx in advence

Edited by nacerbaaziz
Link to post
Share on other sites
  • Developers

So have you looked at and tested with the UDF  I pointed you to if that is what you want as your answer is still not conclusive?

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites
  • Developers

Your last post is a statement which doesn't make much sense to me, unless it was meant as some sort of question? 😕
So Yes, did you try the _WinAPI_IsElevated() UDF to see if that does what you want?

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites

@Jos
I'm sorry if I bothered you.
yes i read the UDF
_WinAPI_IsElevated ( )
is not have params to select the pid or name of process
so, what i need to is a function that give me if any process is runing as admin or not, e.g Notepad.exe or Chrome.exe ....eetc
i hope that i can find that.
thx

Edited by nacerbaaziz
Link to post
Share on other sites
  • Developers

Indeed it is about the current process elevation level. 
I couldn't find an already made UDF so made a copy of the UDF and added the option for a PID. Just have a try with this _WinAPI_IsElevated_pid($iPID) version:

#RequireAdmin
#include <WinAPIProc.au3>

ConsoleWrite('Current process = ' & _WinAPI_IsElevated_pid() & '   >Error code: ' & @error & @CRLF) ;### Debug Console
; Display a list of Notepad processes returned by ProcessList.
Local $aProcessList = ProcessList()
For $i = 1 To $aProcessList[0][0]
    ConsoleWrite($aProcessList[$i][0] & ' = ' & _WinAPI_IsElevated_pid($aProcessList[$i][1]) & '   >Error code: ' & @error & @CRLF) ;### Debug Console
Next

; #FUNCTION# ====================================================================================================================
; Author.........: Yashied
; Modified.......: jpm. Jos
; ===============================================================================================================================
Func _WinAPI_IsElevated_pid($iPID=0)
    Local $aAdjust, $hToken, $iElev, $aRet, $iError = 0
    ; Enable "SeDebugPrivilege" privilege for obtain full access rights to another processes
    Local $hToken = _WinAPI_OpenProcessToken(BitOR($TOKEN_ADJUST_PRIVILEGES, $TOKEN_QUERY))
    _WinAPI_AdjustTokenPrivileges($hToken, $SE_DEBUG_NAME, $SE_PRIVILEGE_ENABLED, $aAdjust)

    If $iPID <> 0 then
        Local $hProcess = DllCall('kernel32.dll', 'handle', 'OpenProcess', 'dword', (($__WINVER < 0x0600) ? 0x00000400 : 0x00001000), _
                'bool', 0, 'dword', $iPID)
        If @error Or Not $hProcess[0] Then Return SetError(@error + 20, @extended, 0)
        $hToken = _WinAPI_OpenProcessToken(0x0008, $hProcess[0])
    Else
        $hToken = _WinAPI_OpenProcessToken(0x0008)
    EndIf
    If Not $hToken Then Return SetError(@error + 10, @extended, False)

    Do
        $aRet = DllCall('advapi32.dll', 'bool', 'GetTokenInformation', 'handle', $hToken, 'uint', 20, 'uint*', 0, 'dword', 4, _
                'dword*', 0) ; TOKEN_ELEVATION
        If @error Or Not $aRet[0] Then
            $iError = @error + 10
            ExitLoop
        EndIf
        $iElev = $aRet[3]
        $aRet = DllCall('advapi32.dll', 'bool', 'GetTokenInformation', 'handle', $hToken, 'uint', 18, 'uint*', 0, 'dword', 4, _
                'dword*', 0) ; TOKEN_ELEVATION_TYPE
        If @error Or Not $aRet[0] Then
            $iError = @error + 20
            ExitLoop
        EndIf
    Until 1
    DllCall("kernel32.dll", "bool", "CloseHandle", "handle", $hToken)
    If $iError Then Return SetError($iError, 0, False)

    Return SetExtended($aRet[0] - 1, $iElev)
EndFunc   ;==>_WinAPI_IsElevated_pid

EDIT: Updated the code after some more testing. Obviously you need to run this elevated to get info from elevated processes. 

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites

@Jos

that exact what i need to

but it have a small problem the function always return 1

here is what i tried

#RequireAdmin
#include <WinAPIProc.au3>
$list = ProcessList("CMD.exe")
if not @Error then
for $i = 1 to $list[0][0]
if _WinAPI_IsElevated_pid($list[$i][1]) then
MSGBox(64, "", 1)
else
MSGBox(64, "", 0)
endIf
next
endIf



; #FUNCTION# ====================================================================================================================
; Author.........: Yashied
; Modified.......: jpm. Jos
; ===============================================================================================================================
Func _WinAPI_IsElevated_pid($iPID)
    Local $iElev, $aRet, $iError = 0

    Local $hProcess = DllCall('kernel32.dll', 'handle', 'OpenProcess', 'dword', (($__WINVER < 0x0600) ? 0x00000400 : 0x00001000), _
            'bool', 0, 'dword', $iPID)
    If @error Or Not $hProcess[0] Then Return SetError(@error + 20, @extended, 0)

    Local $hToken = _WinAPI_OpenProcessToken(0x0008, $hProcess)
    If Not $hToken Then Return SetError(@error + 10, @extended, False)

    Do
        $aRet = DllCall('advapi32.dll', 'bool', 'GetTokenInformation', 'handle', $hToken, 'uint', 20, 'uint*', 0, 'dword', 4, _
                'dword*', 0) ; TOKEN_ELEVATION
        If @error Or Not $aRet[0] Then
            $iError = @error + 10
            ExitLoop
        EndIf
        $iElev = $aRet[3]
        $aRet = DllCall('advapi32.dll', 'bool', 'GetTokenInformation', 'handle', $hToken, 'uint', 18, 'uint*', 0, 'dword', 4, _
                'dword*', 0) ; TOKEN_ELEVATION_TYPE
        If @error Or Not $aRet[0] Then
            $iError = @error + 20
            ExitLoop
        EndIf
    Until 1
    DllCall("kernel32.dll", "bool", "CloseHandle", "handle", $hToken)
    If $iError Then Return SetError($iError, 0, False)

    Return SetExtended($aRet[0] - 1, $iElev)
EndFunc   ;==>_WinAPI_IsElevated_pid

 

i hope you can help me

Link to post
Share on other sites
  • Developers
8 minutes ago, nacerbaaziz said:

but it have a small problem the function always return 1

Have you tried my last example?   that should show also many non elevated processes (0). 

EDIT: Also started a cmd.exe and ran my script which returned 

cmd.exe = 0   >Error code: 0

So all looks correct to me. :) 

Edited by Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites

@Jos
thank you very much
the last example is working successFully
Merci beaucoup

#RequireAdmin
#include <WinAPIProc.au3>
$list = ProcessList("CMD.exe")
if not @Error then
for $i = 1 to $list[0][0]
if _WinAPI_IsElevated_pid($list[$i][1]) then
MSGBox(64, "", 1)
else
MSGBox(64, "", 0)
endIf
next
endIf



; #FUNCTION# ====================================================================================================================
; Author.........: Yashied
; Modified.......: jpm. Jos
; ===============================================================================================================================
Func _WinAPI_IsElevated_pid($iPID=0)
    Local $aAdjust, $hToken, $iElev, $aRet, $iError = 0
    ; Enable "SeDebugPrivilege" privilege for obtain full access rights to another processes
    Local $hToken = _WinAPI_OpenProcessToken(BitOR($TOKEN_ADJUST_PRIVILEGES, $TOKEN_QUERY))
    _WinAPI_AdjustTokenPrivileges($hToken, $SE_DEBUG_NAME, $SE_PRIVILEGE_ENABLED, $aAdjust)

    If $iPID <> 0 then
        Local $hProcess = DllCall('kernel32.dll', 'handle', 'OpenProcess', 'dword', (($__WINVER < 0x0600) ? 0x00000400 : 0x00001000), _
                'bool', 0, 'dword', $iPID)
        If @error Or Not $hProcess[0] Then Return SetError(@error + 20, @extended, 0)
        $hToken = _WinAPI_OpenProcessToken(0x0008, $hProcess[0])
    Else
        $hToken = _WinAPI_OpenProcessToken(0x0008)
    EndIf
    If Not $hToken Then Return SetError(@error + 10, @extended, False)

    Do
        $aRet = DllCall('advapi32.dll', 'bool', 'GetTokenInformation', 'handle', $hToken, 'uint', 20, 'uint*', 0, 'dword', 4, _
                'dword*', 0) ; TOKEN_ELEVATION
        If @error Or Not $aRet[0] Then
            $iError = @error + 10
            ExitLoop
        EndIf
        $iElev = $aRet[3]
        $aRet = DllCall('advapi32.dll', 'bool', 'GetTokenInformation', 'handle', $hToken, 'uint', 18, 'uint*', 0, 'dword', 4, _
                'dword*', 0) ; TOKEN_ELEVATION_TYPE
        If @error Or Not $aRet[0] Then
            $iError = @error + 20
            ExitLoop
        EndIf
    Until 1
    DllCall("kernel32.dll", "bool", "CloseHandle", "handle", $hToken)
    If $iError Then Return SetError($iError, 0, False)

    Return SetExtended($aRet[0] - 1, $iElev)
EndFunc   ;==>_WinAPI_IsElevated_pid

 

Link to post
Share on other sites
  • Developers

@nacerbaaziz....  great :) 

 

@jpm,

Would it be an idea to update the current _WinAPI_IsElevated() with the above version as it is compatible with the option to supply the process PID?

Jos 

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Iraj
      Hi Team,
      Greetings!
       
      One silly doubt, I need to pass one parameter using RunWait to write an output to a file using Cmd Line, but the below isn't writing to the file specified. Kindly assist.
      $pass = $CmdLine[1] $CMD = "C:\Progra~1\bin\Encrypt.exe" &$pass& " > C:\temp\pwd.txt" #write the parameter $pass in C:\temp\pwd.txt RunWait(@ComSpec & " /c " & $CMD,"",@SW_HIDE) Thank you!!
    • By photonblaster
      I am looking for advice on next trouble shooting steps for my problem.  I have researched this over the last three days and still not solved it.  The main reason "run Scite works, exe doesnt" occurs seems to be duplicate names in executable files but I made sure I do not have that problem.
      I have a "trivial" script that watches for a login window to pop up, inserts PW and enter/closes.  It worked for a year then I experimented with #RequireAdmin on another problem and ran/compiled this one with RequireAdmin to check out what happens as a learning excercise.  Now the compiled version MUST be run with admin rights, and I get the UAC approval window  which I must avoid in my application, but the SciTe editor version runs from the tools menu (F5) just fine, no UAC.  The correlation between using RequireAdmin for a while  and the run problem is probably just a coincidence, but I am suspicious.
       
      #include <MsgBoxConstants.au3> ;#RequireAdmin ;trying with and without #requireadmin Opt("SendCapslockMode", 0) ;make sure caps are off Send("{CapsLock off}") Local $myTitle = "User Login Dialog" Local $myPW = "password" & "{ENTER} ; Wait max 10 seconds for the Sign In window to appear. If Not (WinWait($myTitle, "", 10)) Then MsgBox($MB_SYSTEMMODAL + $MB_ICONERROR, "Error", "LogIn window did not appear or is timed out") EndIf If WinActivate($myTitle) Then ControlSend($myTitle, "", "", $myPW ) ;alternate, also works in editor ;Send($myPW & "{ENTER}") ;MsgBox($MB_SYSTEMMODAL + $MB_ICONERROR, "INFO", "SENT $myPW enter") Else MsgBox($MB_SYSTEMMODAL + $MB_ICONERROR, "Error", "Sign In Window did not activate") EndIf Sleep(2000) If (WinExists($myTitle)) Then MsgBox($MB_SYSTEMMODAL + $MB_ICONERROR, "Error", "LOGIN FAILED") EndIf More info that may be relevant, at least as background info: The LogIn window is from a custom addin to Excel, does not have control ID access to the user/pw entry locations, just the enter/cancel buttons are found by AU3Info.  Thus I had to resort to Send, or ControlSend with just the default selection on popup of where the entries go.  Fortunately the UserID area remains populated between uses and the PW entry "window" is automatically selected at window popup so I just enter PW text and {enter}.
      I can run the compiled file as administrator, OK the UAC window "do you want to allow...", and it runs. (right click the file in file explorer, select "Run as Administrator".
      Trying to accept this issue I tried ways to "bypass" the UAC window.   I followed instructions on CNET to run the exe file as administrator automatically but the UAC window still comes up: Always run a program in administrator mode in Windows 10 - CNET
      I tried to create a shortcut to the exe file through the scheduler following these instructions (other links give the same set of instructions), did not seem to run at all, could not track down any errors I might have made. Open any program as administrator without UAC prompt (winaero.com)
      Is there any system settings permanently changed by RequireAdmin?  What should I look at to have the exe file run without the UAC window?
      Regards and stay healthy!
    • By mLipok
      A new quick/small UDF.
      #include-once #include <AutoItConstants.au3> #include <MsgBoxConstants.au3> Global $RUN_WRAPPER_PID Global Enum _ $RUNWRAPPER_ERR_SUCCESS, _ $RUNWRAPPER_ERR_GENERAL, _ $RUNWRAPPER_ERR_COUNTER Global Enum _ $RUNWRAPPER_EXT_DEFAULT, _ $RUNWRAPPER_EXT_NOT_FINISHED_YET, _ $RUNWRAPPER_EXT_COUNTER If Not @Compiled And @ScriptName = 'Run_Wrapper.au3' Then _Example_for_Run_Wrapper() Func _Example_for_Run_Wrapper() _Run_Wrapper('ping 8.8.8.8') If @error then Return SetError(@error, @extended, 0) While $RUN_WRAPPER_PID Sleep(10) _Run_Wrapper_GetStdout() If @error Then _Run_Wrapper_GetStderr() If @error Then ExitLoop EndIf WEnd MsgBox($MB_OK + $MB_TOPMOST + $MB_ICONINFORMATION, 'Information #' & @ScriptLineNumber, _ _Run_Wrapper_GetStdout() & @CRLF & _ _Run_Wrapper_GetStderr() _ ) EndFunc ;==>_Example_for_Run_Wrapper Func _Run_Wrapper($sCommand) _Run_Wrapper_GetStdout(Null) _Run_Wrapper_GetStderr(Null) $RUN_WRAPPER_PID = Run(@ComSpec & " /c " & $sCommand, @SystemDir, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD) If @error Then Return SetError($RUNWRAPPER_ERR_GENERAL, $RUNWRAPPER_EXT_DEFAULT, 0) Return $RUN_WRAPPER_PID EndFunc ;==>_Run_Wrapper Func _Run_Wrapper_GetStdout($v_Reset = Default) Local Static $s_StdOut = "" If IsKeyword($v_Reset) And $v_Reset = Null Then $s_StdOut = '' $s_StdOut &= StdoutRead($RUN_WRAPPER_PID) If @error Then Return SetError(@error, $RUNWRAPPER_EXT_DEFAULT, $s_StdOut) Return SetExtended($RUNWRAPPER_EXT_NOT_FINISHED_YET, $s_StdOut) EndFunc ;==>_Run_Wrapper_GetStdout Func _Run_Wrapper_GetStderr($v_Reset = Default) Local Static $s_StdErr = '' If IsKeyword($v_Reset) And $v_Reset = Null Then $s_StdErr = '' $s_StdErr &= StderrRead($RUN_WRAPPER_PID) If @error Then Return SetError(@error, $RUNWRAPPER_EXT_DEFAULT, $s_StdErr) Return SetExtended($RUNWRAPPER_EXT_NOT_FINISHED_YET, $s_StdErr) EndFunc ;==>_Run_Wrapper_GetStderr  
       
    • By DesireDenied
      Hey guys,
      I having some hard times getting false-positive, probably because I am trying to execute my AutoUpdater.
      Here is my code:
       
      Global $iUpdateTimer = 0 While 1 checkUpdates(10) WEnd Func checkUpdates($iDelay = 10) $iDelay = $iDelay * 1000 * 60 If TimerDiff($iUpdateTimer) > $iDelay Then ConsoleWrite('checking for updates...' & @CRLF) $iUpdateTimer = TimerInit() If FileExists('AutoUpdater.exe') Then ShellExecuteWait('AutoUpdater.exe') ; this is the line which cause my problem EndIf EndFunc And AutoUpdater code:
      #include <MsgBoxConstants.au3> #include <FileConstants.au3> Global $sExecName = 'test.exe' Global $sUpdatePath = @UserProfileDir &'\desktop\AnyAppName\update\'& $sExecName Global $sUserPath = @UserProfileDir &'\desktop\AnyAppName\'& $sExecName Global $sCopyright = 'someUniqueStringHere' If Not FileExists($sUpdatePath) Then Exit 0 If FileGetVersion($sUpdatePath, $FV_LEGALCOPYRIGHT) <> $sCopyright Then Exit 0 ; checking if we really want to update and execute the file If FileGetVersion($sUpdatePath) > FileGetVersion($sUserPath) Then $iResponse = MsgBox(BitOR($MB_YESNO, $MB_ICONQUESTION),'AnyAppName', 'There is an update available, would you like to update?') If $iResponse == $IDYES Then If ProcessExists($sExecName) Then ProcessClose($sExecName) Sleep(500) EndIf FileCopy($sUpdatePath, $sUserPath, $FC_OVERWRITE) Sleep(3000) ShellExecute($sUserPath) Exit 1 EndIf EndIf Exit 0 I am not trying to ask, why is my code is getting recognized as false-positive, because this is quite obvious, but is there any other way to get things done without running external process?
       

    • By WoodGrain
      Hi All,
      Trying to open windows explorer to a WebDav location and it's not working quite how I want, on the computers it is setup as a "network location" (as opposed to a "mapped drive", and this unfortunately can't be changed), the "Data" WebDav folder sits directly under "This PC" if that's an easier way to get to it. any suggestions as to what I can correct to get the 2nd example to work?
      ; This works, but I'm trying to avoid this as users normally see the URL style in the 2nd example below $folderToOpen = "\\mycompany.sharepoint.com@SSL\DavWWWRoot\Data" Run("Explorer.exe " & $folderToOpen) ; This does not work, it tries to open the WebDav url in the default web browser $folderToOpen = "https://mycompany.sharepoint.com/Data" Run("Explorer.exe " & $folderToOpen) ShellExecute also opens it in the default browser.
      Saw _WinAPI_ShellOpenFolderAndSelectItems but couldn't get the 2nd example to work.
      If I manually open Windows Explorer and paste in https://mycompany.sharepoint.com/Data it loads the WebDav directory without issue.
      If I have to use the pathing from the first example it is fine, just trying to give users a familiar experience.
      Thanks!
×
×
  • Create New...