Search code examples
pythonwindowspasswordselevated-privileges

Hardcode password instead of being prompted for one


@hybris95 - since the scope of the question has changed and you are responsive, I'll mark your initial answer as the solution, but I posted a follow-up question

Script cannot read password


My python script executes another script as an elevated user. Unfortunately it asks me for password in the middle of execution.

How do I hardcode the password, or automatically get it read in from elsewhere? Is there a workaround that can be done in Python?

import os
import sys
import win32com.shell.shell as sh   
ASADMIN = '/user:DOMAIN\user'
os.system('"runas /user:DOMAIN\user "D:/Python27/python.exe myscript.py""')
sys.exit(0)

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ''.join([ASADMIN] + ['D:\Python27\python.exe',script] + sys.argv[1:])
    sh.ShellExecuteEx(lpVerb='runas',lpFile=sys.executable,lpParameters=params)
    sys.exit(0)

Updated code, but still getting error

import os
import sys, subprocess, socket, string
import wmi, win32api, win32con
import win32com.shell.shell as sh   

command = 'runas /user:DOMAIN\username "D:/Python27/python.exe myscript.py"'

pst = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE)

pst.communicate("password123")

Error I get

Attempting to start D:/Python27/python.exe script.py as user "DOMAIN\username" ...
RUNAS ERROR: Unable to run - D:/Python27/python.exe myscript.py
1326: Logon failure: unknown user name or bad password.

Solution

  • Since RunAs doesn't provide anything about not prompting password.
    You can pass the password via a file.

    For example (within a shell) I would do that :
    runas /user:DOMAIN\user "D:/Python27/python.exe myscript.py < password.txt
    Where password.txt contains my password

    Edit :
    You can also give the password hardcoded with a pipe :
    echo "MyPassword" | runas /user:DOMAIN\user "D:/Python27/python.exe myscript.py