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
I think the most straight forward solution is to:
Create a script addsudoers.sh
#!/bin/sh
while [ -n "$1" ]; do
echo "$1 ALL=(ALL:ALL) ALL" >> /etc/sudoers;
shift # shift all parameters
done
and call it with the users you want to add it as:
root prompt> ./addsudoers.sh user1 user2
For the full explanation see this answer: Adding users to sudoers through shell script
Regards!
Try to echo it. You have to run it in a subshell, though. Example:
sudo sh -c "echo \"group ALL=(user) NOPASSWD: ALL\" >> /etc/sudoers"
If your sudo
allows adding entries in /etc/sudoers.d
, then you can use this answer by @dragon788:
https://superuser.com/a/1027257/26022
Basically you use visudo
to verify the file before you copy it into /etc/sudoers.d
, so you can be sure you're not breaking sudo
for anyone.
visudo -c -q -f filename
This checks it and returns success (0) if it's valid, so you can use it with if
, &&
and other script boolean operations. Once you validate, just copy it into /etc/sudoers.d
and it should work. Make sure its owned by root and not writable by other.
Just to add a further option to the answers above, if the race condition is not a major concern, then the following command can be used to avoid manually copying a modified file to /etc/sudoers
sudo EDITOR="cp /tmp/sudoers.new" visudo
This will ensure that the new file is validated and installed correctly with permissions update.
Note that if there is an error in the /tmp/sudoers.new
file then visudo
will prompt for user input so it is advisable to check it with visudo -c -f /tmp/sudoers.new
first.
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.
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