Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell and Python - How to run a command as admin

I am writing a code in python in which I need to get the internet traffic by software's name. It's required of me to use the cmd command netstat -nb, command which requires elevation. I have to keep it simple, something of one line or so, no long batch or powershell scripts. It's preferable if I use only the subprocess python library.

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

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

The problem in this one is that a new window it's opened and all the data I need is lost. Maybe there's a way of not opening another window or saving the output from the new window?

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

This one I have the output in the same window but I don't have elevation so I don't get any results... Maybe there is a way of getting elevation without opening a new window or so?

Thank you for your help, hope my question was clear enough.

like image 722
Pedro Peck Avatar asked Nov 07 '22 20:11

Pedro Peck


1 Answers

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

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

Then execute that in your program:

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

It would probably be a bit more bullet-resistent to get the TEMP environment variable and use it for a fully-qualified tempfile location:

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

And then get do the same in your Python script.

Once you've created the tempfile, you should be able to process it in Python.

If this needs to be durable with multiple worker processes, add some code to ensure you have a unique tempfile for each process.

like image 133
Steven K. Mariner Avatar answered Nov 14 '22 21:11

Steven K. Mariner