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:

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?

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.


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

Then execute that in your program:

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

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.


Powershell and Python – How to run a command as admin by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply