MacOS – Remove sudoers using script

bashcommand linemacossudo

At the moment I'm working on a solution to prevent all admins users (except one particular) from running sudo. I can add a specific user to sudoers by running:

sudo -i
echo '$username  ALL=(ALL:ALL) ALL' >> /etc/sudoers

Then I'd like to remove %admin ALL = (ALL) ALL within sudoers file which would just leave the above admin as the only sudo admin. However I cannot seem to find a way on how to remove/replace a particular string within sudoers.

I'd like to make this into a script hence using visudo and manually adjusting won't work for me. If there a way to run visudo from script and adjust a particular line within sudoers that would be ideal, but I couldn't find anything when researching on the Web.

I've seen a solution here:

which works in Linux. Is it possible to make it work in macOS?

Best Answer

Here's an alternate method. Lines are not added or deleted from the sudoers file. The line giving admin root rights is commented out and we create a separate file with mac_admin's rights in the directory /etc/sudoers.d. And as a bonus, the original sudoers file is backed up.

printf '%s\n' 'mac_admin  ALL=(ALL:ALL) ALL' > /tmp/99-macadmin

visudo -c -f /tmp/99-macadmin &&
install -o 0 -g 0 -m 440 /tmp/99-macadmin /etc/sudoers.d

sed $'s/%admin\t/# %admin/' /etc/sudoers > /tmp/sudoers

visudo -c -f /tmp/sudoers &&
install -B .orig -b -o 0 -g 0 -m 440 /tmp/sudoers /etc/sudoers

rm /tmp/sudoers /tmp/99-macadmin