Using sudo with Python script

python, shell, subprocess

Solution

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'
p = os.system('echo %s|sudo -S %s' % (sudoPassword, command))

Try this and let me know if it works. :-)

And this one:

`os.popen("sudo -S %s"%(command), 'w').write('mypass')`

Problem

I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting. The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer it to make sudo by its own. I already know that it is not safe to write your password into a .py file, but we are talking about a virtual machine that is not critical at all: I just want to click the .py script and get it working. This is my attempt: ``` #!/usr/bin/env python import subprocess sudoPassword = 'mypass' command = 'mount -t vboxsf myfolder /home/myuser/myfolder' subprocess.Popen('sudo -S' , shell=True,stdout=subprocess.PIPE) subprocess.Popen(sudoPassword , shell=True,stdout=subprocess.PIPE) subprocess.Popen(command , shell=True,stdout=subprocess.PIPE) ``` My python version is 2.6

Original source

Related problems