- Как дать Root права пользователю в Linux
- Способ 1: Добавление в корневую группу с помощью usermod
- Способ 2: Добавление в корневую группу с помощью команды Useradd
- Способ 3: Редактирование файла /etc/passwd
- Способ 4: Дать права пользователя Sudo
- How to Add a User to the Root Group
- Adding a User
- Debian-based Systems (e.g., Ubuntu)
- Red Hat-based Systems (e.g., CentOS, RHEL, Fedora)
- Verification
- Ubuntu
- CentOS, RHEL, Fedora
- Conclusion
- Dimitri Nek
- Shell Script to Give Root Privileges to a User
- Method 1: Adding to Root Group using usermod
- Method 2: Adding to Root Group using useradd Command
- Method 3: Editing /etc/passwd file
- Method 4: Setting as Sudo User
- Method 5: To give root privileges to a user using a script
- Method 6: Using an interactive dialog box
Как дать Root права пользователю в Linux
Суперпользователь « root ” — это король пользователей Linux / Unix . Наличие корневого доступа предоставляет полный и неограниченный доступ к дистрибутиву Linux .
В этой инструкции я покажу вам, как дать root права пользователю в системе Linux . Как правило, доступ на корневом уровне (root) используется в системном администрировании. Поэтому всегда больно давать root-доступ другим пользователям. Вы должны быть очень осторожны и должны забрать доступ, как только необходимость в этом отпадет.
Согласно разрешениям файловой системы Linux , root или суперпользователь имеет полные права на чтение (r), запись (w) и выполнение (x) любого файла. По умолчанию идентификатор пользователя root равен «0».
Я собираюсь создать двух пользователей, а именно user1 и user2 . Затем я предоставлю root-правак пользователю « user1 «.
Способ 1: Добавление в корневую группу с помощью usermod
Давайте посмотрим, как мы можем дать обычному пользователю root- права, добавив его в корневую группу.
Это группы, которые есть в моей дистрибутиве Linux.
Я собираюсь добавить user1 в корневую группу следующим образом:
Приведенная ниже команда даст пользователю привилегию root
Способ 2: Добавление в корневую группу с помощью команды Useradd
Я добавил нового пользователя « user3 » в корневую группу с помощью команды:
useradd -c “Imitation Root” -d /home/root_user -m -k /etc/skel -s /bin/bash -u 0 -o -g root root_user
Способ 3: Редактирование файла /etc/passwd
Отредактируйте /etc/passwd для конкретного пользователя. Измените UID и GID пользователя на « 0 «. Это даст root права пользователю в linux.
Теперь пользователь temproot должен иметь привилегии root :
Способ 4: Дать права пользователя Sudo
Конфигурационный файл sudo — это файл /etc/sudoers , и вы можете отредактировать его с помощью команды visudo:
Использование visudo защищает от конфликтов и гарантирует использование правильного синтаксиса.
Чтобы предоставить полный доступ конкретным пользователям
Добавьте в файл запись, приведенную ниже:
Следовать этому методу не очень хорошая идея, потому что это позволяет и User1, и User2 использовать команду su для предоставления постоянных привилегий root . Таким образом пропуская функции ведения журнала команд sudo .
Предоставление доступа к определенным файлам одному конкретному пользователю
Эта запись позволяет User 1 и всем другим членам группы получить доступ ко всем программным файлам в каталогах /sbin и /usr/sbin , а также привилегию выполнения команды /usr/oracle/backup.pl…
Если у вас есть какие-либо вопросы или предложения по этой теме, оставьте комментарий.
How to Add a User to the Root Group
Adding a user to the root group is generally not recommended, as it grants the user the same privileges as the root user, which can lead to security risks and unintended consequences. However, if you understand the risks and still want to proceed, you can add a user to the “wheel” group instead. The “wheel” group usually has sudo privileges, allowing its members to execute commands as the root user by using the sudo command.
Adding a User
Here’s how to add a user to the “wheel” group on different Linux distributions:
Debian-based Systems (e.g., Ubuntu)
On Debian-based systems, the “sudo” group is used instead of the “wheel” group. To add a user to the “sudo” group, open a terminal and run the following command, replacing “username” with the actual username:
sudo usermod -aG sudo username
Red Hat-based Systems (e.g., CentOS, RHEL, Fedora)
On Red Hat-based systems, you can add a user to the “wheel” group with the following command, replacing “username” with the actual username:
sudo usermod -aG wheel username
After running the command, the user will need to log out and log back in for the changes to take effect.
Verification
To verify if a user has been added to the “wheel” or “sudo” group, follow the instructions below based on your Linux distribution:
Ubuntu
On Debian-based systems, the “sudo” group is used to grant sudo privileges. To verify if a user is a member of the “sudo” group, open a terminal and run the following command, replacing “username” with the actual username:
The command will display a list of groups the user is a member of. Look for the “sudo” group in the output.
CentOS, RHEL, Fedora
On Red Hat-based systems, the “wheel” group is used to grant sudo privileges. To verify if a user is a member of the “wheel” group, open a terminal and run the following command, replacing “username” with the actual username:
The command will display a list of groups the user is a member of. Look for the “wheel” group in the output.
If the “wheel” or “sudo” group is present in the output, the user has been added to the respective group and will have sudo privileges.
Conclusion
It’s important to remember that granting a user sudo privileges effectively gives them root access. This should only be done for trusted users who require elevated permissions to perform specific tasks. Be cautious when providing sudo access, as it can lead to security risks and unintended consequences if misused.
By following the provided instructions, you can add and verify users in the “wheel” or “sudo” group, depending on your Linux distribution. This allows you to manage user access to elevated privileges on your system while maintaining proper security practices.
Please feel free to leave comments and suggest improvements to this guide. Your feedback is valuable and helps us improve our content for our audience.
Dimitri Nek
Dimitri is a Linux-wielding geek from Newport Beach and a server optimization guru with over 20 years of experience taming web hosting beasts. Equipped with an arsenal of programming languages and an insatiable thirst for knowledge, Dimitri conquers website challenges and scales hosting mountains with unmatched expertise. His vast knowledge of industry-leading hosting providers allows him to make well-informed recommendations tailored to each client’s unique needs.
Shell Script to Give Root Privileges to a User
The sudo command is the most powerful command in Linux. It provides a mechanism for granting administrator privileges, using administrator privileges a normal user can do whatever he wants with the file system of the installed Linux system. Using sudo we can modify our system.
Method 1: Adding to Root Group using usermod
usermod command in Linux is used to modify the user account. Using usermod command we can assign groups, permissions to a specific user. There are mainly 7 groups in the Linux file system, these are as follows:
To add a user to root using usermod, we have to run the following command in the terminal.
Here, the –G flag stands for Group and the root is the group for new user1.
To add an existing user to the root group, follow the following command:
Here, the -g flag stands for Group id, and 0 represents the root group id, and the -o flag is for the existing user.
Method 2: Adding to Root Group using useradd Command
useradd command can be used to create a new user or update default new user information. It is a low-level utility for adding users. To add a user to the group using the useradd command, simply run the following command in your terminal.
Here, the –m flag is used to create the user’s home directory if it does not exist, and the -G flag represents the group.
Method 3: Editing /etc/passwd file
Open up the passwd file using any text editor, and change the group user id to 0 which represents root permission.
Run the following command in the terminal :
Then modify the following permission for the user whom you want to give root access to.
Before giving root permissions:
root:x:0:0:root:/root:/bin/bash user:128:128:user
After giving root permissions
root:x:0:0:root:/root:/bin/bash user:0:0:user
Here, if you see clearly we have modified line 2 that has the user whom we want to give root access, previously it has a value of 128 which is not a group ID for root. So we modified that line and replace the value with the 0, which represents the root group. After that, save the file and reboot your system.
Method 4: Setting as Sudo User
To add a user to sudo user, we can modify the sudoers file located at /etc/sudoers. Open up the sudoers file using any text editor and add the following line at the end of the file to add a user to the sudo user.
Here, ALL represents that we are giving all(full permissions) to the user i.e. the user can run any command and the user just has to authenticate.
- The first ALL is all hosts. i.e. if you have shared this sudoers file to many computers
- The second ALL is the user as you are running the command
- The third ALL is that user can run the command.
Method 5: To give root privileges to a user using a script
To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user.
#!/usr/bin/sudo bash . The rest of the shell script goes here .
Shell Script to make directory using root privileges:
#!/usr/bin/sudo bash echo "Enter a directory name" read newdir `mkdir $newdir`
Save the above script as geeks.sh, to run the script type the following command in the terminal:
Method 6: Using an interactive dialog box
We can use a tool called whiptail to create an interactive dialog box. To install this tool, run the following command in your terminal:
sudo apt install whiptail
#!/usr/bin/bash # saving user's name in me variable me="$(whoami)" # Checking that the script is running as root. # entering in if case if [ "$(id -nu)" != "root" ]; then # resetting cached credentials sudo --reset-timestamp # creating a dialog box to enter user password pswd=$(whiptail --title "GeeksforGeeks Authentication Script" \ --passwordbox "To run this script, administrative privilege is \ required. \n[sudo] Password for user $me:" 14 52 3>&2 2>&1 1>&3-) # executing the script with the password entered by user exec sudo --stdin --prompt '' "$0" "$@"In this script firstly we have created an interactive dialog prompt box for the user to enter the sudo password, then running the script with sudo permissions. Firstly, we are saving the user’s name in me variable for displaying the name in the interactive dialog box. Then using the id command with the if statement we’re checking if the running script is using the root permission, if not we are entering the if statement. Using sudo –reset-timestamp will clear the previously saved credentials and ask for the root password again. Then we have used the whiptail command to add a title, a password box in the interactive dialog box. Here 14 and 52 are the height and width of the dialog box respectively.
“3>&2 2>&1 1>&3-“, we are swapping stdout and stderr.
The 3>&2 in the script will create a new file descriptor and redirect it to 2 which is stderr. Now 2>&1 will redirect the file descriptor 2 to stdout and 1>&3 will redirect file descriptor 1 to 3 which is stdout. And save the password into pswd variable.
If the user enters the wrong password 3 times, we are exiting the script and displaying exit code 1. And after finishing the if block, we can do the stuff that needs root permission. In this script, we are creating a folder after getting root permission.