pythonwindowsbatch-fileadministrator

How to make Python script run as Administrator in Windows?


I trying to embed a Batch script use to activating Windows into a Python script, but the script need to run as Administrator in Windows so I find different solution, but none works. Here is the latest code:

import subprocess
import sys

batch_script = """
@echo off
set "scriptver=v0.1.2"

:setup
>nul reg add hkcu\software\classes\.Admin\shell\runas\command /f /ve /d "cmd /x /d /r set \"f0=%%2\"&                   call \"%%2\" %%3"& set _= %*
>nul fltmc|| if "%f0%" neq "%~f0" (cd.>"%temp%\\runas.Admin" & start "%~n0" /high "%temp%\\runas.Admin" "%~f0" "%_:"=""%" & exit /b)

title Test
echo commands here
rem more commands here
"""

# Save the Batch script to a temporary file
with open('temp_batch_script.bat', 'w') as batch_file:
    batch_file.write(batch_script)

# Run the Batch script as a subprocess   
try:
    subprocess.run(['cmd', '/c', 'temp_batch_script.bat'], check=True)
except subprocess.CalledProcessError as e:
    print(f"Error running Batch script: {e}")
finally:
# Clean up temporary file
    subprocess.run(['del', 'temp_batch_script.bat'], shell=True, check=True)

I tried finding solution on the web, applied them, but none out of 3 I found works.


Solution

  • make a new file called run.py and give it this content:

    imort os    
    os.system("runas /user:Administrator \"path/to/your/first.file.py\"")
    

    Run this file instead of the first one, and it will run as admin.