User is not in the sudoers file this incident will be reported как исправить

Если вы создали нового пользователя в Ubuntu, и пытаетесь от его имени использовать систему, то при попытке выполнения команды sudo можете столкнуться с ошибкой: «user is not in the sudoers file this insident will be reported».

В этой небольшой инструкции мы рассмотрим почему возникает такая ошибка, а также как ее обойти и разрешить этому пользователю выполнять действия от суперпользователя.

Команда sudo позволяет обычным пользователям выполнять программы от имени суперпользователя со всеми его правами. Использовать команду sudo могут далеко не все пользователи, а только те, которые указаны в файле /etc/sudoers. Это сообщение об ошибке говорит буквально следующее — вашего пользователя нет в файле sudoers, а значит доступ ему к утилите будет запрещен, а об этом инциденте будет сообщено администратору.

Все неудачные попытки использовать sudo, независимо от того, был ли введен неверный пароль или у пользователя нет прав, действительно записываются в каталоге /var/log, так что вы можете посмотреть кто и когда и что пытался выполнить:

tail /var/log/auth.log

Исправление ошибки с помощью root

Для исправления ситуации достаточно добавить пользователя sudoers. Но для этого нужно иметь другого пользователя, который может использовать sudo. Если такой пользователь есть, задача становиться довольно простой. Но если кроме текущего пользователя в системе нет больше никого, проблема тоже вполне решаема.

Начнем с более простого варианта, на тот случай, если у вас все-таки есть доступ к системе от имени пользователя root. Войдите от имени пользователя, у которого есть права, например, можно нажать Ctrl+Alt+T запустить утилиту su и ввести пароль:

su

В большинстве случаев в файле sudoers настроено так, что утилиту могут использовать все пользователи из группы wheel или sudo. Поэтому достаточно добавить нашего пользователя в эту группу. Для этого используйте команду usermod.

usermod -a -G wheel имя_пользователя

Или:

usermod -a -G sudo имя_пользователя

Вы также можете добавить нужную настройку для самого пользователя в файл sudoers, для этого добавьте в конец файла такую строку:

имя_пользователя ALL = (ALL) ALL

Дальше осталось сохранить изменения в файле и заново зайти под именем нужного пользователя. Если в файле /etc/sudoers не разрешено использование утилиты пользователями из группы wheel или sudo, то можно добавить такую строчку:

vi /etc/sudoers

%wheel ALL = (ALL) ALL

Или для группы sudo:

%sudo ALL = (ALL) ALL

Возможно, её будет достаточно расскоментировать, убрать решетку, которая расположена перед ней. После этого ошибка user is not in the sudoers file исчезнет и вы сможете использовать sudo. Более подробно про это все вы можете прочитать в статье настройка sudo.

Исправление ошибки с помощью режима восстановления

Если на вашем компьютере нет другого пользователя, от имени которого вы могли бы получить доступ к sudo, осталась возможность использовать режим восстановления. Для этого перезагрузите компьютер и в меню Grub нажмите E.

Откроется редактор меню загрузки. В нем найдите строку:

linux vmlinuz...

И в конец добавьте init=/bin/bash. Должно получиться вот так:

linux vmlinuz... init=/bin/bash

Дальше вы загрузитесь в оболочку /bin/bash с правами суперпользователя и от туда уже сможете выполнить все выше приведенные команды, например, добавить пользователя sudoers, добавлением его в группу wheel:

usermod -a -G wheel имя_пользователя

После выполнения команды можно перезагрузить компьютер с помощью команды reboot. Следующая загрузка пройдет в нормальном режиме и вы сможете использовать sudo.

Выводы

В этой статье мы рассмотрели что делать, если вы получаете ошибку user is not in the sudoers file, а также как добавить пользователя в sudoers ubuntu чтобы ее избежать. Если у вас остались вопросы, спрашивайте в комментариях!

На завершение видео про добавление пользователя в sudores:

https://youtu.be/-fUwk2TNfQ8

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

After logging into ssh, I got this message:

‘Username’ is not in the sudoers file. This incident will be reported.

How can I resolve this? I’m connecting ssh to my virtual private server.

Promise Preston's user avatar

asked Dec 14, 2017 at 5:43

Danish Arman's user avatar

3

Open file

su root 
nano /etc/sudoers

Then add the user below admin user like below syntax.

user_name ALL=(ALL)  ALL

answered Dec 14, 2017 at 6:20

sanath meti's user avatar

sanath metisanath meti

4,8591 gold badge21 silver badges30 bronze badges

11

Both the above answers are correct as far as they go but it is easier to add your user to the sudo group in debian based systems (Ubuntu, kbuntu, debian, etc) and the wheel group under RedHat based systems (RedHat, Fedora, CentOS, etc)

usermod -a -G sudo user
or
usermod -a -G wheel user 

answered Dec 14, 2017 at 10:13

Rodney Howard's user avatar

7

This is a very common error for the beginners.
The error occurs because we are trying to access/update something with super privileges from the user instead of root -user.

Hence, to solve this,we need to make changes in the sudoers file where the root user has been given the privileges. So, switch to root user,run the following command

sudo su 
# vi /etc/sudoers

The editor would open the file, now scroll down to the bottom where you will see a line

#User privilege specification

root     ALL=(ALL:ALL) ALL

username ALL=(ALL:ALL) ALL

As you can see, I have just added my username with all permissions.

Save the file, and exit. Switch back to the user and start using sudo commands with ease.

answered Jul 20, 2019 at 12:12

Sonal 's user avatar

Sonal Sonal

5795 silver badges7 bronze badges

3

At the top of the aforementioned /etc/sudoers file there’s an info:

"## This file MUST be edited with the 'visudo' command as root."

In order of doing as we’re told, use:

$ su
> Enter root password: *******
$ visudo -f /etc/sudoers

Find the following section of /etc/sudoers file and add your users privileges:

# User privilege specification
root    ALL=(ALL:ALL) ALL
user_name ALL=(ALL) ALL

Save the file (press esc and type :x if vim is your default text editor, for nano press ctrl+o, enter and then ctrl+x).

Type exit to turn off the root shell, and enjoy the power of sudo with your username

answered Dec 9, 2019 at 20:06

wscourge's user avatar

wscourgewscourge

10.4k14 gold badges57 silver badges79 bronze badges

You should use visudo to edit /etc/sudoers file.

Just run
sudo visudo -f /etc/sudoers

and add your username with correct syntax and access rights.
You can find more in man sudoers

snowpeak's user avatar

snowpeak

7689 silver badges25 bronze badges

answered Dec 14, 2017 at 9:39

Viktor Khilin's user avatar

Got a slightly different syntax to Rodney’s from my host

usermod -aG wheel username

Their explanation was

The user will need to be added to the wheel group.

Use the usermod command to add the user to the wheel group.

You may need to log off and log back in after doing this

answered Jul 5, 2018 at 15:41

Robert Sinclair's user avatar

Robert SinclairRobert Sinclair

4,4602 gold badges41 silver badges44 bronze badges

3

If you’re unable to find visudo on your system

whereis visudo

Launch this tool

./PATH/visudo

add this line under

User privilege specification

user_name ALL=(ALL)  ALL

Save the changes and here you go !

answered May 11, 2020 at 12:19

Olivier D'Ancona's user avatar

Olivier D’AnconaOlivier D’Ancona

7402 gold badges14 silver badges29 bronze badges

  1. Entered Root using command $ su root. Input Root Password

  2. Install sudo: $ apt-get install sudo -y

  3. Add your < username> $ adduser <username> sudo

  4. $ exit

  5. Then sign up and sign in the < username> session

  6. Finally, check with: < username>@< hostname>:~$ sudo apt-get update

answered Jun 13, 2019 at 19:20

Braian Coronel's user avatar

Braian CoronelBraian Coronel

21.8k4 gold badges55 silver badges60 bronze badges

1

try this video, it works for me.

  1. ssh root@localhost
  2. sudo vi /etc/sudoers
  3. insert username in file ‘sudoers’
  4. save and exit ssh

Dharman's user avatar

Dharman

30.3k22 gold badges84 silver badges132 bronze badges

answered Dec 30, 2020 at 3:35

user6670135's user avatar

First, switch/ log into the root user account or an account that has sudo privileges.

Next add the user to the group for sudo users:

  • If you’re on Ubuntu members of the sudo group are granted with sudo privileges, so you can use this:

    sudo adduser username sudo
    
  • If you’re on CentOS members of the wheel group are granted with sudo privileges, so you can use this::

    usermod -aG wheel username
    

Note: Replace username with your desired username.

To test the sudo access, log into the account that you just added to the sudo users grouP, and then run the command below using sudo:

sudo whoami

You will be prompted to enter the password. If the user have sudo access, the output will be:

root

If you get an error saying user is not in the sudoers file, it means that the user doesn’t have sudo privileges yet.

That’s all.

I hope this helps

answered Sep 18, 2020 at 14:34

Promise Preston's user avatar

Promise PrestonPromise Preston

22.8k12 gold badges137 silver badges140 bronze badges

Add your user to the list of sudoers. This will make it easier to execute
commands as the user that you have created will require admin privileges.

sudo adduser username sudo

(Note:- Username is the user you want to give the privileges)

answered Apr 15, 2020 at 4:35

Tej's user avatar

1

I am running Ubuntu 12.04 on my laptop using VMware Player. I am not sure why but I have an account called «User Account» in addition to my account that I usually login to use Ubuntu. Well that was just a side comment but basically all I am trying to do is install the ncurses library on Ubuntu. I have tried installing ncurses using the following command lines:

sudo apt-get install libncurses5-dev
sudo apt-get install ncurses-dev

When I tried installing ncurses twice using the above commands I received the following prompt in the terminal:

[sudo] password for username

When I type in my password I receive the following message:

username is not in the sudoers file. This incident will be reported.

So far I have tried enabling the root user («Super User») account by following these instructions.

Here are some of the things the link suggested to do:

Allow an other user to run sudo. Type the following in the command line:

sudo adduser username sudo

Or

sudo adduser username sudo

logging in as another user. Type the following in the command line:

sudo -i -u username

Enabling the root account. Type the following in the command line:

sudo -i

Or

sudo passwd root

I have tried all of the above command lines and after typing in each command I was prompted for my password. After I entered my password I received the same message as when I tried to install ncurses:

fsolano is not in the sudoers file. This incident will be reported.

Это краткое руководство по устранению проблемы «user is not in the sudoers file in Linux» в Linux/UNIX. Проблема вызвана тем, что пользователь не имеет доступа sudo в вашей системе и может быть быстро исправлена путем добавления пользователя в группу wheel с помощью команды usermod или путем редактирования файла sudoers в вашей системе Linux.

В этом руководстве я собираюсь показать вам два быстрых метода решения проблемы «user is not in the sudoers file in Linux», чтобы дать вашему пользователю доступ к sudo.

Способ 1: Использование команды usermod

Сначала узнайте, какое у вас имя пользователя, открыв терминал и выполнив приведенную ниже команду. Пропустите этот шаг, если вы уже знаете свое имя пользователя.

Переключите пользователя на root с помощью команды su:

Добавьте своего пользователя в группу wheel, выполнив следующую команду. Замените <username> на имя пользователя, указанное в шаге 1 выше.

sudo usermod -aG wheel [имя пользователя]

Выйдите из системы и войдите в нее (или перезагрузите), чтобы изменения вступили в силу. Проверьте, входит ли ваш пользователь в группу wheel, выполнив в терминале команду:

Теперь ваш пользователь может выполнять команды, требующие повышения прав, с помощью sudo в Linux без проблем.

Метод 2: Использование файла sudoers

Этот метод исправит проблему «пользователь отсутствует в файле sudoers» путем редактирования файла /etc/sudoers.

Сначала переключите пользователя на root с помощью команды su. Введите пароль root, когда появится запрос.

Отредактируйте файл sudoers, используя редактор vi или любой другой удобный для вас редактор.

либо

Прокрутите вниз, пока не найдете root ALL=(ALL) ALL и добавьте следующую строку под ним. Замените <имя пользователя> на ваше настоящее имя пользователя.

[ваше имя пользователя] ALL=(ALL) ALL

Вот как должен выглядеть ваш файл sudoers.

sudoers

Сохраните и выйдите из файла. Выйдите из системы и снова войдите в нее (или перезагрузите), чтобы изменения вступили в силу.

Теперь вы сможете выполнять команды с sudo в Linux/UNIX без каких-либо проблем. Это руководство было протестировано на нескольких других дистрибутивах Linux (Debian, Ubuntu, Arch), а также в UNIX (FreeBSD).

Вот и все. Вот как исправить ошибку «пользователя нет в файле sudoers» в Linux. Надеюсь, вы нашли этот пост полезным.

In Unix/Linux systems, the root user account is the super user account, and it can therefore be used to do anything and everything achievable on the system.

However, this can be very dangerous in so many ways – one could be that the root user might enter a wrong command and breaks the whole system or an attacker gets access to root user account and takes control of the whole system and who knows what he/she can possibly do.

Based upon this background, in Ubuntu and its derivatives, the root user account is locked by default, regular users (system administrators or not) can only gain super user privileges by using the sudo command.

And one of the worst things that can happen to a Ubuntu System admin is losing privileges to use the sudo command, a situation commonly referred to as “broken sudo”. This can be absolutely devastating.

A broken sudo may be caused by any of the following:

  1. A user should not have been removed from the sudo or admin group.
  2. The /etc/sudoers file was altered to prevent users in sudo or admin group from elevating their privileges to that of root using sudo command.
  3. The permission on /etc/sudoers file is not set to 0440.

In order to perform crucial tasks on your system such as viewing or altering important system files, or updating the system, you need the sudo command to gain super user privileges. What if you are denied usage of sudo due one or more of the reasons we mentioned above.

Below is an image showing a case in which the default system user is being prevented from running sudo command:

[email protected] ~ $ sudo visudo
[ sudo ] password for aaronkilik:
aaronkilik is not in the sudoers file.   This incident will be reported.

[email protected] ~ $ sudo apt install vim
[ sudo ] password for aaronkilik:
aaronkilik is not in the sudoers file.   This incident will be reported.

How To Fix Broken sudo Command in Ubuntu

If you happen to be running only Ubuntu on your machine, after powering it, press the Shift key for a few seconds to get the Grub boot menu. On the other hand, if you are running a dual-boot (Ubuntu alongside Windows or Mac OS X), then you should see the Grub boot menu by default.

Using the Down Arrow, select “Advanced options for Ubuntu” and press Enter.

Ubuntu Grub Menu

Ubuntu Grub Menu

You will be at the interface below, select the kernel with “recovery mode” option as below and press Enter to advance to the “Recovery menu”.

Ubuntu Recovery Mode

Ubuntu Recovery Mode

Below is the “Recovery menu”, indicating that the root filesystem is mounted as read-only. Move over to the line “root Drop to root shell prompt”, then hit Enter.

Ubuntu Recovery Menu - Drop to root Shell Prompt

Ubuntu Recovery Menu – Drop to root Shell Prompt

Next, press Enter for maintenance:

Ubuntu Maintenance

Ubuntu Maintenance

At this point, you should be at the root shell prompt. As we had seen before, the filesystem is mounted as read-only, therefore, to make changes to the system we need to remount is as read/write by running the command below:

# mount -o rw,remount /

Solving Case #1 – Add User to sudo or admin Group

Assuming that a user has been removed from the sudo group, to add user back to sudo group issue the command below:

# adduser username sudo

Note: Remember to use the actual username on the system, for my case, it is aaronkilik.

Or else, under the condition that a user has been removed from the admin group, run the following command:

# adduser username admin

Solving Case #2 – Granting sudo Privileges to Users

On the assumption that the /etc/sudoers file was altered to prevent users in sudo or admin group from elevating their privileges to that of a super user, then make a backup of the sudoers files as follows:

# cp /etc/sudoers /etc/sudoers.orginal

Subsequently, open the sudoers file.

# visudo

and add the content below:

#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbi$

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

Solving Case #3 – Setting Correct Permission on sudoers File

Supposing that the permission on /etc/sudoers file is not set to 0440, then run following command to make it right:

# chmod  0440  /etc/sudoers

Last but not least, after running all the necessary commands, type the exit command to go back to the “Recovery menu”:

# exit 

Use the Right Arrow to select <Ok> and hit Enter:

Ubuntu Recovery Menu - Resume Normal Boot

Ubuntu Recovery Menu – Resume Normal Boot

Press <Ok> to continue with normal boot sequence:

Confirm Ubuntu Normal Boot

Confirm Ubuntu Normal Boot

Summary

This method should work just fine especially when it is an administrative user account involved, where there is no other option but to use the recovery mode.

However, if it fails to work for you, try to get back to us by expressing your experience via the feedback section below. You can as well offer any suggestions or other possible ways to solve the issue at hand or improve this guide altogether.

Понравилась статья? Поделить с друзьями:
  • Как найти разрядность ацп
  • Как найти шифр телефона
  • Как по рисунку найти тангенс тупого угла
  • Как найти распределение сил тока
  • Дота 2 как найти гильдию по названию