2

How do I get python to run sudo openvpn --cd /etc/openvpn --config client.ovpn

I'm trying the following at the minute without success

vpnfile2 = '/etc/init.d/openvpn'
cfgFile = 'client.ovpn'

os.system('sudo \"" + vpnFile2 + "\" --cd \"" + vpnpath + "\" --config \"" + cfgFile + "\"')
3
  • I'm not certain that executing sudo in this context will work. I believe you need an interactive session in order to run commands with sudo. Consider omitting the "sudo" and instead running the Python script with the appropriate permissions. Commented Mar 7, 2010 at 21:58
  • @chradcliffe, easy enough to try it subprocess.call(['sudo', 'cat', '/etc/shadow']) :) Works ok on Karmic by the way! Perhaps some versions of sudo don't Commented Mar 7, 2010 at 22:17
  • @gnibbler You're right. I guess it just seems a little odd to do it this way; however, I suppose if you only need privilege escalation for a single command, you could make a case for this approach. Commented Mar 7, 2010 at 23:55

3 Answers 3

8

use the subprocess module

import subprocess
subprocess.call(['sudo', vpnFile2, '--cd', vpnpath, '--config', cfgFile])
1

This question has been posted awhile ago, but if someone comes across this (like me), there is another way to get privileges using the os.system method ..

It will only work if you are running this in a GUI environment. You can simply try to call it with 'gksu' or ('kdesu' or 'kdesudo'), it would look like this in a gnome session:

import os
vpnfile2 = '/etc/init.d/openvpn'
cfgFile = 'client.ovpn'

os.system('gksu \"" + vpnFile2 + "\" --cd \"" + vpnpath + "\" --config \"" + cfgFile + "\"')

The prompt works, but I have not tested it to work with your code.

0

If there is some reason you want to use os.system, instead of subprocess, I usually wash it through bash, so os.system('''sudo bash -c "command to run"''') (Or sh or whatever shell you have). It processes the arguments better in many cases.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.