How to do visudo edit in sudoers.d automatically in Python?

48 Views Asked by At

I have a complex django-application and want to add the option for the user to shutdown the server (a Raspberry Pi) from the django-webmenu. Because the django-process on the Raspi does not have sudo privileges, I decided to give the shutdown privilege to my user via an additional configfile in sudoers.d. So I added two lines to execute to my installation instructions: To create the new file with visudo:

sudo visudo -f /etc/sudoers.d/shutdown_privilege

And than add one line to that file:

cam_ai ALL=(root) NOPASSWD: /sbin/shutdown

This works nicely, but now I would like to move this complication into my (Python-)installation script. This does not work. What am I doing wrong?

I tried several things:

subprocess.call(['sudo', 'touch', '/etc/sudoers.d/shutdown_privilege']) 
subprocess.call(['sudo', 'sed', '-i', '$acam_ai ALL=(root) NOPASSWD: /sbin/shutdown' , '/etc/sudoers.d/shutdown_privilege']) 

cmd = 'echo "cam_ai ALL=(root) NOPASSWD: /sbin/shutdown" | sudo tee -a /etc/sudoers.d/shutdown_privilege'
subprocess.call(cmd, executable='/bin/bash')

The only thing that worked is the touch command in the first line. The rest stops the program execution or does just nothing...

0

There are 0 best solutions below