Search code examples
pythonpython-3.xpyautogui

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.


Solution

  • 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.