Linux user add root permission

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.

Читайте также:  Перезагрузить сетевую карту linux

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.

Источник

Как дать Root права пользователю в Linux

Суперпользователь «root” — это король пользователей Linux / Unix. Наличие корневого доступа предоставляет полный и неограниченный доступ к дистрибутиву Linux.

В этой инструкции я покажу вам, как дать root права пользователю в системе Linux. Как правило, доступ на корневом уровне (root) используется в системном администрировании. Поэтому всегда больно давать root-доступ другим пользователям. Вы должны быть очень осторожны и должны забрать доступ, как только необходимость в этом отпадет.

Как дать Root права пользователю в Linux

Согласно разрешениям файловой системы 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

Если у вас есть какие-либо вопросы или предложения по этой теме, оставьте комментарий.

Источник

How To Add a User and Grant Root Privileges on Ubuntu 18.04

Adding a user and granting that user root privileges is one of the many tasks of a system admin. Once a user has been added and granted root privileges they’ll be able to login to your Ubuntu VPS and perform vital functions for the upkeep of the system. Afterward, they’ll be able to use sudo before commands to perform elevated tasks. In this quick tutorial, we’ll show you how to add a new user and grant root permissions.

How To Add a User and Grant Root Privileges on Ubuntu 18.04

Preflight

  • These instructions are intended specifically for adding a user on Ubuntu 18.04 LTS.
  • We'll be working from a Liquid Web Core Managed Ubuntu 18.04 LTS server, and I’ll be logged in as root.

Step 1: Add the Username

In my example, I’ll be adding my cat’s name, Tom, using the adduser command. Replace tom with your desired username. During this time, the system will also ask of me details from my user. Feel free to skip these details by pressing enter and eventually it asks us to confirm that the info is correct, leading us to a new user added.

Example Output:
Adding user `tom' .
Adding new group `tom' (1001) .
Adding new user `tom' (1001) with group `tom' .
Creating home directory `/home/tom' .
Copying files from `/etc/skel' .
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for tom
Enter the new value, or press ENTER for the default
Full Name []: Tom
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] Y

Step 2: Grant Root Privileges to the User

The command above leads us to the /etc/sudoers.tmp file, where we can view the following code: # User privilege specification
root ALL=(ALL:ALL) ALL

After the root user line, you will add in your new user with the same format for us to grant admin privileges.

Once you’ve added the permission, save and exit the file by using the following process. (In Ubuntu 18.04, nano is the default editor, so we need to use the ctrl+x, y keystrokes to save and exit the file.)

hold `ctrl` and press `x`. At the prompt, press `y` and then hit `enter` to save and exit the file.

Step 3: Verify User Has Privileges

If you’ve followed the instructions correctly then this user will be able to run commands like, update, using the sudo:

Want to do admin tasks through a control panel? Check out our servers that come with cPanel. We offer assisted migrations and 24/7 support making it effortless to switch to Liquid Web!

About the Author: Justin Palmer

Justin Palmer is a professional application developer with Liquid Web

Refer a Friend

Join our mailing list to receive news, tips, strategies, and inspiration you need to grow your business

Источник

Оцените статью
Adblock
detector