Skip to main content

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.



I've seen a possible solution here:



https://www.ibm.com/developerworks/community/blogs/brian/entry/edit_sudoers_file_from_a_script4?lang=en
which works in Linux. Is it possible to make it work in macOS?

Hi @ben.merkys,



you could use sed



sed -i "" "s/String2replace/NewString/g" /etc/sudoers


This "" is needed because of the special version of sed macOS uses.



BR
Daniel


Remove admin rights from current logged in user --



#!/bin/sh

# grab current user

curUser=`ls -l /dev/console | cut -d " " -f 4`

/usr/sbin/dseditgroup -o edit -d $curUser -t user admin


--- make current user admin

dscl . -append /Groups/admin GroupMembership $curUser

I've found a solution for this by writing a script to back up the original sudoers file and rename it to sudoers.orig, comment out the %admin in the duplicated file and add my preferred user to sudoers.d



Combined with a recurring Jamf Policy, this solution works -



printf '%s
' '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 /# %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


To undo changes, a simple

rm

and
mv

are requited to delete the edited sudoers file and rename the sudoers.orig back to sudoers.


@ben.merkys



Hey sorry to dredge up an old post!



We have been using your above script to great use to change our sudoers file.



I am still new to bash scripting, so was wondering where you would need to add the



rm


and



mv


To change the file? Thanks!


@scotscollege



Hi there,



Sorry for the very late reply, hope you see this.



The rm command is to be executed separately as this would remove the edited sudoers file from the machine altogether.



We then use mv command to rename the backed up sudoers file to its original name, by writing mv adding a space, the name of the file, another space, and the new name you wish the file to have.


would there be any concerns if I used composer to build a package from a clean machine with the default sudoers file and then install that with a policy to users machines? So far i've tested this and it works.