Powershell and Python - How to run a command as an administrator

I am writing python code in which I need to get internet traffic by software name. I needed to use the cmd netstat -nb command, a command requiring promotion. I have to keep it simple, something like a single line or so, without long scripts or scripts. This is preferable if I only use the python subprocess library.

I have two lines of code that work halfway through what I need:

 subprocess.check_output('powershell Start-Process netstat -ArgumentList "-nb" -Verb "runAs"', stdout=subprocess.PIPE, shell=True) 

The problem is that the new window that it opened and all the data I need is lost. Maybe there is a way not to open another window or save the output from a new window?

 subprocess.check_output('powershell Invoke-Command {cmd.exe -ArgumentList "/c netstat -nb"}', stdout=subprocess.PIPE, shell=True) 

I have output in the same window, but I have no elevation, so I am not getting any results ... Maybe there is a way to get the elevation without opening a new window, or so?

Thank you for your help, I hope that my question will be clear enough.

+5
source share
1 answer

Create a batch file to perform the task with captured output to the temp file:

 [donetstat.bat] netstat -nb > ".\donetstat.tmp" 

Then do this in your program:

 [yourprogram.py] subprocess.check_output('powershell Start-Process cmd -ArgumentList "/c ".\donetstat.tmp" -Verb "runAs"', stdout=subprocess.PIPE, shell=True) 

Probably, to get the TEMP environment variable and use it for a fully functional location of the temporary file, it would be a little more than bulletproof:

 netstat -nb > "%TEMP%.\donetstat.tmp" 

And then do the same in your Python script.

After creating the temporary file, you can process it in Python.

If this is necessary for a long process with multiple workflows, add some code to make sure you have a unique tempfile for each process.

+1
source

Source: https://habr.com/ru/post/1269127/


All Articles