Sarthak Mahapatra
Sarthak Mahapatra

Reputation: 133

Unable to open CMD as admin using Python Pyautogui

I am trying to open CMD as admin using Python 3.7 pyautogui. I am able to navigate to the start menu icon, type 'cmd' and press ctrl + shift +enter for opening cmd in admin mode.

Then a pop-up message comes up with yes or no whether to open as admin or not. When I am using pyautogui.press('left'), it is not pressing the left button.

try:
    import pyautogui
    import time
    pyautogui.FAILSAFE = True
    pyautogui.PAUSE = 0.5
    mouseMovementDuration = 2 #every mouse movement will take 2 secs
    intervalBetweenKeyPress = 0.5
    def runCMDasAdmin():
        x, y = pyautogui.locateCenterOnScreen(r'C:\\Users\\Saru\\Desktop\\PyAutoGUI\\images\\startmenu.png')
        pyautogui.click(x=x, y=y,button='left',duration=mouseMovementDuration) 
        pyautogui.typewrite('cmd', interval=intervalBetweenKeyPress)
        pyautogui.hotkey('ctrl', 'shift', 'enter')
        pyautogui.press(['left','enter'],interval=intervalBetweenKeyPress)

    print(pyautogui.size()) #It will give you the size of the screen
    pyautogui.moveTo(x=1919,y=1079,duration=mouseMovementDuration)
    pyautogui.moveTo(x=1,y=1,duration=mouseMovementDuration)
    runCMDasAdmin()
except Exception as e:
    print("Exception Raised------>",str(e))

I want to open cmd as admin using pyautogui. Please help.

Upvotes: 1

Views: 2768

Answers (2)

Sarthak Mahapatra
Sarthak Mahapatra

Reputation: 133

As the User Access Control (UAC) prompt works on a separate layer beyond the control of any automation/code component for user's security. So the only solution is to disable UAC prompts completely. The procedure to disable UAC prompts - On start menu type UAC, select User Access Control settings, set it to never notify.

Upvotes: 1

Naveen
Naveen

Reputation: 788

You can use batch script to open CMD as Admin. Below is the code.

@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

Upvotes: 0

Related Questions