0

I need to run netstat -nb via python code but everything I tried gives me the same output, "The requested operation requires elevation."

How do I evaluate netstat -nb in python?

Tony M
  • 329
  • 5
  • 13
  • 1
    It might be helpful to review [this related](https://stackoverflow.com/questions/19672352/how-to-run-python-script-with-elevated-privilege-on-windows). – jedwards Jun 24 '18 at 18:10

2 Answers2

1

other approach with os module:

import os
output_command = os.popen("netstat -nb").readlines()

The argument -b is only for windows and the error message mean that you need administrator permissions.

Baurin Leza
  • 2,004
  • 1
  • 13
  • 15
0

Have you tried:

from subprocess import Popen, PIPE

p = Popen(['netstat', 'nb'], stdout=PIPE, stderr=PIPE)

stdout, stderr = p.communicate()
print(stdout)
Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57
  • I have tried that before, It gives me the same output: "The requested operation requires elevation." – Tony M Jun 25 '18 at 10:22
  • Are you running it on Windows? If yes, try: p = Popen(['runas', '/noprofile', '/user:Administrator', 'netstat','nb'],stdin=PIPE, stdout= PIPE) p.stdin.write('password') stdout, stderr = p.communicate() I have not tried this as I am Ubuntu and there the fore worked without asking for sudo. Another way is to run this command in administrator CMD mode. ;) – Prayson W. Daniel Jun 25 '18 at 10:39