dextervip dextervip - 1 year ago 270
Python Question

How to run cmd windows netsh command using python?

I am trying to run the following netsh command on Windows 7 however It returns incorrect syntax

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("netsh interface ipv4 set interface ""Conex√£o de Rede sem Fio"" metric=1")
The syntax of the file name, directory name or volume label is incorrect.


What's wrong?

Answer Source

os.systemis a very old choice and not really recommended.

Instead you should consider or subprocess.Popen().

Here is how to use them:

If you don't care about the output, then:

import subprocess
...'netsh interface ipv4 set interface ""Wireless Network" metric=1', shell=True)

If you do care about the output, then:

netshcmd=subprocess.Popen('netsh interface ipv4 set interface ""Wireless Network" metric=1', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE )
output, errors =  netshcmd.communicate()
if errors: 
   print "WARNING: ", errors
   print "SUCCESS ", output
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download