How do I edit /etc/sudoers from a script?
Use visudo for this with a custom editor. This solves all the race conditions and "hack" problems with Brian's solution.
#!/bin/shif [ -z "$1" ]; then echo "Starting up visudo with this script as first parameter" export EDITOR=$0 && sudo -E visudoelse echo "Changing sudoers" echo "# Dummy change to sudoers" >> $1fi
This script will add the line "# Dummy change to sudoers" to the end of sudoers. No hacks and no race conditions.
Annotated version that explains how this actually works:
if [ -z "$1" ]; then # When you run the script, you will run this block since $1 is empty. echo "Starting up visudo with this script as first parameter" # We first set this script as the EDITOR and then starts visudo. # Visudo will now start and use THIS SCRIPT as its editor export EDITOR=$0 && sudo -E visudoelse # When visudo starts this script, it will provide the name of the sudoers # file as the first parameter and $1 will be non-empty. Because of that, # visudo will run this block. echo "Changing sudoers" # We change the sudoers file and then exit echo "# Dummy change to sudoers" >> $1fi
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/shif [ -f "/etc/sudoers.tmp" ]; then exit 1fitouch /etc/sudoers.tmpedit_sudoers /tmp/sudoers.newvisudo -c -f /tmp/sudoers.newif [ "$?" -eq "0" ]; then cp /tmp/sudoers.new /etc/sudoersfirm /etc/sudoers.tmp