How do I edit /etc/sudoers from a script?

Viewed 92938

I need to edit /etc/sudoers from a script to add/remove stuff from white lists.

Assuming I have a command that would work on a normal file, how could I apply it to /etc/sudoers?

Can I copy and modify it, then have visudo replace the original with the modified copy? By providing my own script in $EDITOR?

Or can I just use the same locks and cp?

The question is more about potential issues than about just finding something that works.

14 Answers

You should make your edits to a temporary file, then use visudo -c -f sudoers.temp to confirm that the changes are valid and then copy it over the top of /etc/sudoers

#!/bin/sh
if [ -f "/etc/sudoers.tmp" ]; then
    exit 1
fi
touch /etc/sudoers.tmp
edit_sudoers /tmp/sudoers.new
visudo -c -f /tmp/sudoers.new
if [ "$?" -eq "0" ]; then
    cp /tmp/sudoers.new /etc/sudoers
fi
rm /etc/sudoers.tmp

visudo is supposed to be the human interface for editing /etc/sudoers. You can achieve the same by replacing the file directly, but you have to take care yourself about concurrent editing and syntax validation. Mind the r--r----- permissions.

Lots of answers, been working with sudo for yonks but did not have a need to automate the setup config till now. I used a mix of some of the answers above, writing my config line to the /etc/sudoers.d include location so i don't have to modify the main sudoers file, then checked that file for syntax , simple example below:

Write your line to a sudoers include file:

sudo bash -c 'echo "your_user ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/99_sudo_include_file'

Check that your sudoers include file passed the visudo syntax checks:

sudo visudo -cf /etc/sudoers.d/99_sudo_include_file

Set up a custom editor. Basically it will be a script that accepts the filename (in this case /etc/sudoers.tmp), and modify and save that in place. So you could just write out to that file. When you are done, exit the script, and visudo will take care of modifying the actual sudoers file for you.

sudo EDITOR=/path/to/my_dummy_editor.sh visudo

This is the solution I came up with. It's a quick and dirty solution, but it works...

echo "username ALL=(ALL) NOPASSWD:ALL" | sudo tee -a /etc/sudoers

It pipes the echo output into tee which is running under sudo. Tee then appends the output into the sudoers file.

Since this question has much more pv than this one, and sed is more flexible comparing to tee, I'll just leave the link to a "better" solutin and my solution here.

Based on Valery Panov's answer, I wrote this

echo 's/^#\s*\(%wheel\s*ALL=(ALL)\s*ALL\)/\1/g' | EDITOR='sed -f- -i' visudo

to uncomment this line in /etc/sudoers

# %wheel  ALL=(ALL)       ALL
Related