Is it possible to add users to the sudoers file through a shell script? I've been looking around, still can't find anything.
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
- Null-terminated string, opening file for reading
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"
Other answers such as spawning a subshell will work, but may not work if you want to use environmental vars. One alternative I found played really nicely for me:
This being said, hindsight is 20/20... If modifying sudoers via a script and not via visudo I would seriously recommend creating a backup with the right file permissions and contents first since you can lose access to any sudo rights without pkexec, physical access or a reboot etc.
There is also the
sudo
group, and you could add users to it (for common configurations of/etc/sudoers
)on RedHat Based Distributions use:
and enter your password, then :
to add the user in sudoers file.
Login as root to your machine. The root user are the only one who has privilege to add new user.
Once you logged-in, you may now try the following commands below:
Create a new user.
adduser [username]
Add password to user
passwd [username]
Grant root privileges to user Edit the visudo file by simply typing
enter code here
Find the following line of code: root ALL=(ALL) ALL
Then add this code below:
The original post will find on this link Centos 6 – Creating sudoers user
You could simply
echo
(with elevated privileges, of course) directly to the/etc/sudoers
file:(note the tab character between the username and the first
ALL
)Or, for a script:
Then save to
somefile.sh
,chmod a+rx
it, and runsudo ./somefile.sh
from a terminal window.To add multiple users, change the script to this;
Then, run the script like this (assuming you saved it as
addsudousers.sh
):that is, space-separated.
To read the names from a file:
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 containsecho ... >> /etc/sudoers
and the script itself has superuser privileges, everything should work just fine.