Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

shell

sudo

People also ask

How do I edit sudoers in a script?

Shell script to modify the /etc/sudoers file and give sudo permissions for a user and also to turn requiretty off. # Take a backup of sudoers file and change the backup file. # Check syntax of the backup file to make sure it is correct. # Replace the sudoers file with the new only if syntax is correct.

What command is used to edit the sudoers file?

The syntax for editing these files would be: sudo visudo -f /etc/sudoers. d/ file_to_edit.


Old thread, but what about:

echo 'foobar ALL=(ALL:ALL) ALL' | sudo EDITOR='tee -a' visudo

Use visudo for this with a custom editor. This solves all the race conditions and "hack" problems with Brian's solution.

#!/bin/sh
if [ -z "$1" ]; then
  echo "Starting up visudo with this script as first parameter"
  export EDITOR=$0 && sudo -E visudo
else
  echo "Changing sudoers"
  echo "# Dummy change to sudoers" >> $1
fi

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 visudo
else

  # 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" >> $1
fi

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

On most distributions (at least Debian-based, Redhat-based, openSUSE-based, etc.), you can insert a custom script into the /etc/sudoers.d/ directory, with rights 0440 - For more information see man sudo ("Including other files from within sudo") or the same information on the official site.

It might help.