Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding users to sudoers through shell script

Tags:

linux

sh

sudo

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

like image 810
nickw444 Avatar asked Jan 09 '12 06:01

nickw444


People also ask

How do you add a user to a script?

You can quickly write a shell script that reads username, password from the keyboard, and add a username to the /etc/passwd and store encrypted password in /etc/shadow file using useradd command.


2 Answers

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:

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

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

To add multiple users, change the script to this;

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

Then, run the script like this (assuming you saved it as addsudousers.sh):

sudo ./addsudousers.sh bob joe jeff 

that is, space-separated.

To read the names from a file:

nickw444@laptop ~ $ sudo ./addsudousers.sh `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.

like image 63
wchargin Avatar answered Sep 23 '22 12:09

wchargin


No, a straight echo won't work, you have to run it in a subshell. Try this instead:

sudo sh -c "echo \"group ALL=(user) NOPASSWD: ALL\" >> /etc/sudoers"

like image 44
Apollo Avatar answered Sep 24 '22 12:09

Apollo