1

I'm trying to use python Subprocess module to enable/disable Ethernet connection from python code. Below is my code in which the first step is looking for the available "Ethernet Connections" and the next step enables/disables the ethernet connection according to the parameter passed in "%interfaces%".

for /f "skip=2 tokens=3*" %%A in ('netsh interface show interface') do set interface=%%B

netsh interface set interface %interface%  ENABLED

Now when using in python I couldn't pass the variable, not sure if it's even possible though. Passing only command as below works as expected:

import subprocess
subprocess.call('netsh interface set interface Ethernet10 ENABLED')

I want to do something like:

import subprocess
subprocess.call (set x = 'Ethernet0')
subprocess.call('netsh interface set interface x  ENABLED')
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
Samkeith
  • 55
  • 1
  • 8

2 Answers2

3

subprocess.call takes a list as an argument:

subprocess.call(['netsh', 'interface', 'set', 'interface', x, 'ENABLED'])

You could instead pass shell=True and your string would work, but it is a security risk, since an user could for example call another command by using $(command_here)

If you still want to use a string, you could use shlex.split.

idjaw
  • 25,487
  • 7
  • 64
  • 83
Francisco
  • 10,918
  • 6
  • 34
  • 45
  • thanks idjaw, it worked as expected. One more question now when trying to use subprocess for below code doesn't work. I tried to separate it out in individual strings and in a single string as well using shell=True but didn't helped. for /f "skip=2 tokens=3*" %%A in ('netsh interface show interface') do set interface=%%B – Samkeith Nov 03 '16 at 00:10
  • this is how I seperated. import subprocess y = subprocess.call(['for /f', 'skip=2 tokens=3*', '%%A in', 'netsh', 'interface', 'show', 'interface', 'do', 'set', 'interface=%%B']) print y – Samkeith Nov 03 '16 at 00:16
0

Use string formatting, interpolation, or concatenation:

x = 'Ethernet10'
subprocess.call('netsh interface set interface ' + x + ' ENABLED')
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • 1
    Not quite. The way you are trying to structure that as a single string, you will have to pass `shell=True`. However, the preferred/safer way to do this is to leave `shell=False` and structure the call as a list. Pretty much like the other answer that was just posted. – idjaw Nov 02 '16 at 22:46