Samkeith Samkeith - 1 month ago 9
Python Question

How to parse netsh output using python

I'm getting output as expected using:


import subprocess x = subprocess.call('netsh interface show
interface')


as


Admin State State Type Interface Name
-------------------------------------------------------------------------
Enabled Connected Dedicated Ethernet0


But when trying to parse netsh output as below:


x.split()
Throws error "AttributeError: 'int' object has no attribute 'split'" I tired several other ways but didn't worked.


I am trying to retrieve(filter) just Interface name from netsh output using python.

Answer

subprocess.call just returns the return code, not the output stream of the command.

To do what you want, you could do this instead:

p = subprocess.Popen('netsh interface show interface',stdout=subprocess.PIPE)
[x,err] = p.communicate() 

then x contains the output provided by the netsh program.

As a general remark, note that it's better to pass the arguments in a string like this:

['netsh','interface','show','interface'] 

so you have better control of arguments, and can pass arguments with spaces in it without bothering to quote them, quoting is done by subprocess module.