nickw444 nickw444 - 1 year ago 82
Linux Question

Adding users to sudoers through shell script

Is it possible to add users to the sudoers file through a shell script?
I've been looking around, still can't find anything.

Answer Source

You could simply echo (with elevated privileges, of course) directly to the /etc/sudoers file:

sudo -i
echo 'nickw444  ALL=(ALL:ALL) ALL' >> /etc/sudoers
#             ^^
#             tab

(note the tab character between the username and the first ALL)

Or, for a script:

# Run me with superuser privileges
echo 'nickw444  ALL=(ALL:ALL) ALL' >> /etc/sudoers

Then save to, chmod a+rx it, and run sudo ./ from a terminal window.

To add multiple users, change the script to this;


while [[ -n $1 ]]; do
    echo "$1    ALL=(ALL:ALL) ALL" >> /etc/sudoers;
    shift # shift all parameters;

Then, run the script like this (assuming you saved it as

sudo ./ bob joe jeff

that is, space-separated.

To read the names from a file:

nickw444@laptop ~ $ sudo ./ `cat listofusers.txt`

listofusers.txt should also be space-separated.

Edit: Jappie Kirk rightly points out that you can't directly call sudo echo ... >> /etc/sudoers because the >> redirection is handled by the shell, which has by that point dropped the superuser privileges. However, if you run a script that contains echo ... >> /etc/sudoers and the script itself has superuser privileges, everything should work just fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download