- 1 year ago
How do I start a powershell process with administrator privilges and redirect stdin (os.exec)
You can start a PowerShell process with administrator privileges and redirect standard input (stdin) using the subprocess
module in Python. Here's an example code:
pythonimport subprocess
# command to be executed
command = "powershell.exe"
# arguments for the command
args = ["-ExecutionPolicy", "Bypass", "-NoLogo", "-NoProfile", "-Command", "& {Start-Process PowerShell -Verb RunAs -ArgumentList '-NoLogo', '-NoProfile', '-Command', 'Write-Host \"Hello World!\"'}"]
# create subprocess
p = subprocess.Popen([command] + args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# write input to subprocess
p.stdin.write(b"Hello from stdin\n")
# read output from subprocess
out, err = p.communicate()
# print output
print(out.decode('utf-8'))
In this example, the subprocess.Popen
function is used to start a PowerShell process with administrator privileges. The stdin
argument is set to subprocess.PIPE
to enable input to be sent to the process, and the stdout
and stderr
arguments are set to subprocess.PIPE
to capture the output of the process. The communicate
method is used to send input to the process and retrieve its output.
The command executed in this example starts a new PowerShell process with administrator privileges and runs a command to write "Hello World!" to the console. The Write-Host
command is wrapped in a script block using the & { }
syntax to allow it to be executed as a single argument to the Start-Process
cmdlet. The -ArgumentList
parameter of the Start-Process
cmdlet is used to pass additional arguments to the new PowerShell process, including the -Command
parameter to execute the Write-Host
command.
Note that the subprocess
module provides many other options for controlling the behavior of the subprocess, such as setting environment variables and working directory, specifying timeouts, and redirecting standard output and error.