- HowTo: Grant Root Access to User – Root Privileges – Linux
- Grant Root Privileges To New User
- Grant Root Privileges To Existent User
- Add User To Root Group
- Delete User With Root Privileges
- 46 Replies to “HowTo: Grant Root Access to User – Root Privileges – Linux”
- Как дать Root права пользователю в Linux
- Способ 1: Добавление в корневую группу с помощью usermod
- Способ 2: Добавление в корневую группу с помощью команды Useradd
- Способ 3: Редактирование файла /etc/passwd
- Способ 4: Дать права пользователя Sudo
- 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
HowTo: Grant Root Access to User – Root Privileges – Linux
From this article you’ll learn how to create a user in Linux and grant root access to him or how to grant root privileges to already existent user.
This can be easily done by changing UID (user id) and GID (group id) in /etc/passwd file.
Also you will learn how to just add user to root group and i will explain how to delete user with root privileges.
Actually it is not a good idea to give all the privileges of root to a non-root user and outside the test environment i would not recommend to have multiply superusers.
Warning: Giving a non-root user all the permissions of root is very dangerous, because the non-root user will be able to do literally anything that could cause a big trouble if account is hijacked.
Check SSH Server Settings: If you have disabled root access in SSH server settings, by setting PermitRootLogin no in /etc/ssh/sshd_config – you won’t be able to login if your user has UID 0 .
Warning: Before moving forward, read the comments below and DON’T FOLLOW THE STEPS FROM THIS ARTICLE if you don’t understand of what you are doing and what impact this may have!
Grant Root Privileges To New User
To create a user with exactly the same privileges as root user, we have to assign him the same user ID as the root user has ( UID 0 ) and the same group ID ( GID 0 ).
Use the following commands to create a user john , grand him the same privileges as root and set him a password:
$ sudo useradd -ou 0 -g 0 john $ sudo passwd john
Grant Root Privileges To Existent User
Cool Tip: Dot the i’s and cross the t’s on file and folder permissions in Linux! Make it more clear! Read more →
Perhaps you already have a user john and you want to grant him root privileges (make him a second root user):
$ grep john /etc/passwd john:x:1001:1001::/home/alice:/bin/sh
For this, it is required to edit the file /etc/passwd and just change UID and GID to 0 :
$ grep john /etc/passwd john:x:0:0::/home/john:/bin/sh
Add User To Root Group
If you just want to add john to root group, without granting him all root privileges, run the following command:
$ sudo usermod -a -G root john
Delete User With Root Privileges
Cool Tip: Log in to a remote Linux server without entering password! Set up password-less SSH login! Read more →
You won’t be able to delete a user with UID 0 using userdel command:
$ sudo userdel john userdel: user john is currently used by process 1
To delete him, firstly open the /etc/passwd file and change his UID .
For example, change the line:
After this, you’ll be able to delete user john with userdel command:
46 Replies to “HowTo: Grant Root Access to User – Root Privileges – Linux”
“For this, it is required to edit the file /etc/passwd and just change UID and GID to 0”
WRONG.
Baaaad idea. Much regret. Undo, undo.
ntfs@brix:~$ ssh 192.168.88.16 -l pi
pi@192.168.88.16‘s password:
Permission denied, please try again.
pi@192.168.88.16‘s password:
Permission denied, please try again.
– – –
Nice explanation?)
Since noone elaborate how to undo this broken way of adding users, I will. The only way is to successful login to the linux machine, if you login via ssh or tty.
If you add a user with uid 0 to group uid 0, and you set in sshd_config AllowRootLogin NO, you`re access will be denied. So you will have to login to the linux machine via tty (this is the only way if you don`t have a correctly added backup user on the linux machine). Via tty you can login with any of the users, even root.
The correct way to add a user with root privileges is adding the user the normal way, useradd -m user, and then add privileges with visudo to the user.
So if you have a backup user that haves root privileges in visudo. you will be able to login to the linux machine via ssh, and you will be able to change the uid and group to the “broken” user.
I think this article explains more likely how to add a user with root privileges “the hacker way (which is a broken way)”, and repair the broken way after.
Also if you don`t have access to a tty console, and you want to test the commands of this article and be sure you did not broke something, STAY LOGGED in current session and open another one and test if all things are OK. If you can`t login in the new session, you still have opened the previous session and you can repair what have you broken.
Hope it helps to repair further mistakes.
Как дать Root права пользователю в Linux
Суперпользователь «root” — это король пользователей Linux / Unix. Наличие корневого доступа предоставляет полный и неограниченный доступ к дистрибутиву Linux.
В этой инструкции я покажу вам, как дать root права пользователю в системе Linux. Как правило, доступ на корневом уровне (root) используется в системном администрировании. Поэтому всегда больно давать root-доступ другим пользователям. Вы должны быть очень осторожны и должны забрать доступ, как только необходимость в этом отпадет.
Согласно разрешениям файловой системы Linux, root или суперпользователь имеет полные права на чтение (r), запись (w) и выполнение (x) любого файла. По умолчанию идентификатор пользователя root равен «0».
Я собираюсь создать двух пользователей, а именно user1 и user2. Затем я предоставлю root-правак пользователю «user1«.
Способ 1: Добавление в корневую группу с помощью usermod
Давайте посмотрим, как мы можем дать обычному пользователю root- права, добавив его в корневую группу.
# adduser user1
# adduser user2
# groupadd test
Это группы, которые есть в моей дистрибутиве Linux.
# groups
root bin daemon sys adm disk wheel
Я собираюсь добавить user1 в корневую группу следующим образом:
Приведенная ниже команда даст пользователю привилегию root
Способ 2: Добавление в корневую группу с помощью команды Useradd
Я добавил нового пользователя «user3» в корневую группу с помощью команды:
# useradd -m -G root user3
# groups user3
user3 : user3 root
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:
ВНИМАНИЕ: это не рекомендуемый метод предоставления корневого доступа (root-прав)
Способ 4: Дать права пользователя Sudo
Конфигурационный файл sudo — это файл /etc/sudoers, и вы можете отредактировать его с помощью команды visudo:
Использование visudo защищает от конфликтов и гарантирует использование правильного синтаксиса.
Чтобы предоставить полный доступ конкретным пользователям
Добавьте в файл запись, приведенную ниже:
Следовать этому методу не очень хорошая идея, потому что это позволяет и User1, и User2 использовать команду su для предоставления постоянных привилегий root. Таким образом пропуская функции ведения журнала команд sudo.
Предоставление доступа к определенным файлам одному конкретному пользователю
Эта запись позволяет User 1 и всем другим членам группы получить доступ ко всем программным файлам в каталогах /sbin и /usr/sbin, а также привилегию выполнения команды /usr/oracle/backup.pl…
User1, %operator ALL= /sbin/, / usr/sbin, /usr/oracle/backup.pl
Если у вас есть какие-либо вопросы или предложения по этой теме, оставьте комментарий.
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.