Is not in sudoers file debian как исправить

Решение проблемы с sudo после установки Debian

Сколько раз устанавливал Debian, столько раз сталкивался с одним и тем же – настройкой прав пользователя для использования sudo. Каждый раз забывал и приходилось лезть в интернет, и искать решение. Теперь сам пишу, чтобы не искать следующий раз и вам, возможно, пригодится.

В чем суть

Итак, пользователям Ubuntu хорошо известна такая утилита как sudo, без которой вы не сможете ни установить, ни удалить программу, ни внести какие нибудь весомые изменения в работу системы. В Debian же, пользователи вместо sudo, в основном пользуются учётной записью root. Стоит только посмотреть на инструкции или HOWTO для Debian в интернете – всегда строка начинается сразу из aptitude, что подразумевает то, что  команду нужно выполнять из-под root. Но как по мне – это не есть совсем правильно, плюс годы использования Ubuntu тоже оставляют свой след. К тому же, до сих пор помню свою первую установку Debian, когда после установки KDE из под рута, в обычном сеансе пользователя у меня не работала звуковая подсистема. Сколько тогда для неопытного было мучений!

Для начала, если sudo у вас не установлен, такое может быть, например, если вы устанавливали лишь базовую систему без графической оболочки – установите его:

aptitude install sudo

Как можно догадаться, это делается из под рута. В других случаях sudo должен установиться с системой. Но на этом ещё не конец. Хоть sudo уже установлен, при попытке что нибудь сделать с его использованием, например проверить обновления, терминал выдаст сообщение что user is not in the sudoers file. Чтобы исправить это, существует несколько вариантов действий.

До недавнего времени я соглашался с терминалом и добавлял пользователя, то есть себя, в файл sudoers. Для изменения sudoers файла есть специальная утилита visudo, запускается она командой:

visudo

В открывшимся файле нужно найти строчку:

root ALL=(ALL) ALL

И под ней необходимо добавить такую же, только вместо root пишем свое имя пользователя (username замените на свое):

username ALL=(ALL) ALL

После этого сохранением файл, выходим из visudo, перелогиниваемся и можем пользоваться sudo – ошибка “User is not in the sudoers file” тревожить нас больше не будет. Но так как, по моему мнению, всегда нужно стремится к универсальности, я поступил по другому.

Исправляем “User is not in the sudoers file” (способ №2)

Кроме прямого добавления пользователя в sudoers файл, в него также можно добавлять группы. В данном случае это группа sudo. Процесс добавления группы выглядит точно так же как и добавление пользователя, только вместо имени пользователя нужно вписать группу sudo. Выглядеть это будет так (для обозначения того, что вы добавляете группу, а не пользователя, перед sudo нужно поставить без пробелов знак процента):

%sudo ALL=(ALL) ALL

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

adduser username sudo

Где username – логин пользователя. Затем перелогин и можно работать.

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

На этом все. Если кому поможет буду рад.

This article explains how to «fix» sudo not working on Linux, resulting in this message when trying to use it: «your-username is not in the sudoers file. This incident will be reported.» on Debian (and Debian-based Linux distributions like Ubuntu). sudo allows system admins to execute commands as root (administrator) or another user.

Example from a fresh Debian 10 (10.1) Buster installation on which sudo doesn’t work:

$ sudo apt update
[sudo] password for logix:
logix is not in the sudoers file.  This incident will be reported.

sudo doesn’t work by default on a Fresh Debian installation because your username is not automatically added to the sudo group (it does work on Ubuntu by default). But you may also see this if you created a new user but you forgot to add it to the sudo group, or if another user from your system removed the username from the sudo group.

You can check if the currently logged in user belongs to the sudo group by using the groups command. If the groups command does not return sudo on Debian-based Linux distributions, then that username can’t run commands with sudo. Example with output of a Debian user that’s not in the sudo group:

$ groups
logix cdrom floppy audio dip video pugdev netdev scanner lpadmin

You might like: How To Install The Latest Firefox (Non-ESR) On Debian 10 Buster (Stable) Or Bullseye (Testing)

The solution to this is to add that user to the sudo group. But how do you get root in that case, since you can’t modify or add users as a regular user? Use su - (or sudo su -), then add the user to the sudo group.

So to get root, then add your user to the sudo group, use:

su -
usermod -aG sudo YOUR_USERNAME
exit


Where:

  • su switches to the root user, while - runs a login shell so things like /etc/profile, .bashrc, and so on are executed (this way commands like usermod will be in your $PATH, so you don’t have to type the full path to the executable). You may also use sudo su - instead of su -
  • You need to replace YOUR_USERNAME with the username that you want to add to the sudo group.
  • I have used usermode to add a group to an existing user because it should work on any Linux distribution. adduser or useradd can also be used for this (adduser USERNAME -G sudo) but they may not work across all Linux distributions. Even though this article is for Debian, I wanted to make it possible to use this on other Linux distributions as well (I noticed that adduser doesn’t work on Solus OS for example).
  • exit exists the root shell, so you can run commands as a regular user again.


After this, sudo still won’t work! You will need to logout from that user, then relogin, and sudo will work.

This fixes the «Username is not in the sudoers file.  This incident will be reported» issue on your Debian machine, but you may run into another problem in some cases — sudo might not be installed at all by default. This is the case for example on a minimal Debian installation. In that case you’ll see an error like this when trying to run a command with sudo:

$ sudo apt update
bash: sudo: command not found

In that case, install sudo on Debian like this:

su - #or 'sudo su -'
apt install sudo
exit

A few more Debian-related articles you might like:

  • How To Downgrade Packages To A Specific Version With Apt In Debian, Ubuntu Or Linux Mint
  • How To Show A History Of Installed, Upgraded Or Removed Packages In Debian, Ubuntu or Linux Mint [dpkg]
  • How To List All Packages In A Repository On Ubuntu, Debian Or Linux Mint [APT]
  • How To Find The Package That Provides A File (Installed Or Not) On Ubuntu, Debian Or Linux Mint

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

7

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,3651 gold badge20 silver badges30 bronze badges

14

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

5

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

5095 silver badges6 bronze badges

2

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.1k12 gold badges58 silver badges76 bronze badges

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,2422 gold badges40 silver badges42 bronze badges

3

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

Sushilinux's user avatar

answered Dec 14, 2017 at 9:39

Viktor Khilin's user avatar

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

6812 gold badges14 silver badges28 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.6k4 gold badges53 silver badges59 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

29.3k21 gold badges80 silver badges131 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

21.1k11 gold badges127 silver badges128 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

sudo errorЗачастую при использовании команды sudo можно столкнуться с ошибкой «[имя_пользователя] is not in the sudoers file. This insident will be reported». Выполнить команду при этом не получается. В этой статье поговорим о причине ошибки и о методах её устранения.

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

Решение проблемы видится простым — добавить пользователя в файл sudoers. Можно добавить туда и группу пользователей.

Обратите внимание на пример файла sudoers на скриншоте ниже. Красным выделены учетная запись и группа, которые могут использовать sudo. Как видите, в данном случае её могут использовать пользователь root и пользователи, входящие в группу sudo.

Исправление ошибки user is not in the sudoers file

Пример файла sudoers.

Полный путь к файлу это /etc/sudoers. В принципе, достаточно просто открыть файл от пользователя с правами администратора и откорректировать (если Вы не знаете пароль суперпользователя root, его можно сбросить по рекомендациям из следующей статьи). Но я рекомендую команду visudo, так как она дополнительно проверяет синтаксис файла /etc/sudoers при сохранении. Вариантов несколько:

1. Добавить пользователя

Просто добавьте строку вида

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

2. Добавить группу, в которую входит пользователь

%[имя_группы] ALL=(ALL:ALL) ALL

Однако, возможно, Вы не хотите давать доступ к sudo всем членам этой группы. Тогда этот способ Вам не подойдёт.

3. Добавить пользователя в группу, которой разрешен доступ к sudo

Для этого достаточно отредактировать файл /etc/group. Делать это тоже нужно из-под учетки с правами администратора. Найдите нужную группу в файле /etc/group и впишите в неё имя пользователя.

На скриншоте ниже мы видим, что группа sudo пуста.

Группы в Linux

Впишите имя пользователя после двоеточия и сохраните файл. Если в группе уже есть пользователь или пользователи, новых нужно добавлять через запятую без пробелов.

Другой способ добавления пользователя в группу — команда usermod. Подробнее о группах пользователей в Linux можно прочитать в статье по этой ссылке.

Если выбрать последний из трёх способов, то потребуется перезагрузка.

После вышеописанных действий ошибка user is not in the sudoers file появляться не будет.

This is a quick guide on how to fix the “user is not in the sudoers file” in Linux/UNIX. The issue is caused by your user not having sudo access in your system and can be quickly fixed by adding the user to the wheel group using the usermod command or via editing the sudoers file in your Linux system.

I recently encountered the “user is not in the sudoers file” error when attempting to install NVIDIA drivers in Fedora Silverblue using the sudo command. In Fedora Silverblue you can choose during the installer if you want to grant a user administrative privileges and I probably left this option unchecked.

In this guide, I am going to show you two quick methods to fix the “user is not in the sudoers file” issue to give your user access to sudo. I am going to use Fedora Silverblue but the same procedure should work on any other Linux distribution out there.

Method 1: Using the usermod command

  1. First, find what is your user name by opening a terminal and executing the command below. Skip this step if you already know your user name.
whoami
  1. Switch user to root using the su command:
su -
  1. Add your user to the wheel group by executing the following command. Replacing the <username> with the user name in step 1 above. 
sudo usermod -aG wheel <username>
  1. Log out and log in (or reboot) the system for the changes to take effect.
  2. Check if your user is part of the wheel group by executing in the terminal the command:
groups

Now your user should execute commands that require elevation, with sudo in Linux without issues.

Method 2: Using the sudoers file

This method will fix the “user is not in the sudoers file” by editing the /etc/sudoers file. 

  1. First, switch user to root using the su command. Type your root password when prompted.
su -
  1. Edit the sudoers file using the vi editor or any other editor you are comfortable with. 
visudo
  1. Scroll down until you find root  ALL=(ALL)  ALL and add the following line below it. Replace <username> with your actual user name.
<your username> ALL=(ALL) ALL

Here is how your sudoers file should look like. The new line is underlined in red.

Save and exit the file.

  1. Log out and back in (or reboot) the system for the change to take effect.

You should be able now to run commands with sudo in Linux/UNIX without any issues. This guide was tested on a few other Linux distributions (Debian, Ubuntu, Arch) as well as in UNIX (FreeBSD).

That’s it. This is how you fix the “user is not in the sudoers file” error in Linux. I hope you found this post useful. Be well!

Leonard Cucos

Leonard Cucos is an engineer with over 20 years of IT/Telco experience managing large UNIX/Linux-based server infrastructures, IP and Optics core networks, Information Security [red/blue], Data Science, and FinTech.

I need to install a package. For that I need root access. However the system says that I am not in sudoers file. When trying to edit one, it complains alike! How am I supposed to add myself to the sudoers file if I don’t have the right to edit one?

I have installed this system and only administrator. What can I do?

Edit: I have tried visudo already. It requires me to be in sudoers in the first place.

amarzaya@linux-debian-gnu:/$ sudo /usr/sbin/visudo 

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for amarzaya: 
amarzaya is not in the sudoers file.  This incident will be reported.
amarzaya@linux-debian-gnu:/$ 

asked Mar 15, 2010 at 22:55

Sergiy Belozorov's user avatar

Sergiy BelozorovSergiy Belozorov

1,8528 gold badges29 silver badges42 bronze badges

2

It would be something of a security hole if you could add yourself to /etc/sudoers without having sudo or root access. Basically then anyone could make themselves root.

Basically you need to ask the administrators of that machine to add you, or to install the package for you, as per the policies of the site.

You should also be sure to use visudo to edit the sudoers file — it checks that the syntax is correct before writing the file. And you can use editors other than vi with visudo. It will by default use whatever you have set as $EDITOR and if you don’t have it set you could do

# EDITOR=nano visudo

to use the nano editor instead.

answered Mar 15, 2010 at 23:01

Hamish Downer's user avatar

3

Login as root and use /usr/sbin/visudo to edit the file and add your username. Normal vi/vim will not be able to edit the file.

The easiest way is to just go down until you see the line «root ALL=(ALL) ALL» and add yourself under that with the same syntax (yourusername ALL=(ALL) ALL). Or, you can read the sudoers manpage if you want to give yourself more specific privileges.

answered Mar 15, 2010 at 23:00

Ricket's user avatar

RicketRicket

1,5564 gold badges18 silver badges27 bronze badges

3

Just typed the command:

$ su

And asked for the password «root». Typed and boom… It worked!

This problem was my mistake. Due to be back at the facility at the time I created the username and password.

Kazark's user avatar

Kazark

3,3893 gold badges26 silver badges35 bronze badges

answered Nov 12, 2012 at 11:27

Carlos Trisotto's user avatar

1

Perhaps the easiest way, once you’re root, is:

echo 'amarzaya ALL=(ALL) ALL' >> /etc/sudoers

answered Mar 16, 2010 at 20:15

1

If your sudoers file already contains this kind of line

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

Then, the cleanest way of doing things is probably to grant the admin group to your user. For instance, to add user oracle to the admin group:

usermod -aG admin oracle

answered Jul 6, 2011 at 10:12

Alain Pannetier's user avatar

Alain PannetierAlain Pannetier

7792 gold badges10 silver badges21 bronze badges

5

In case you can still get root access using su, you can use this one-liner to add yourself to /etc/sudoers/:

su -c 'echo $USER ALL=(ALL)ALL >> /etc/sudoers'

To activate the change, log out and in again. For example end your the X Session or log out via shell enter exit.

answered Jul 8, 2012 at 14:48

Bengt's user avatar

BengtBengt

992 bronze badges

1

If you cannot use the sudo command, then you can use the following method:

  1. Press Ctrl+Alt+F1
  2. Log the user out if the user is not root
  3. Log in as root
  4. Use root privileges
  5. Log out (exit) – Ctrl+Alt+F7 to get to the GUI

Synetech's user avatar

Synetech

67.6k35 gold badges221 silver badges352 bronze badges

answered Dec 18, 2013 at 2:52

user3113604's user avatar

1

All you need is add your <username> to whell group.

# usermod -aG whell username

Then login with your username and enjoy :)

answered Jan 20, 2017 at 15:35

EFernandes's user avatar

EFernandesEFernandes

1871 silver badge3 bronze badges

Sign in using the following first:

$ su

Then go ahead with:

$ sudo apt-get update

or whatever as normal

answered Dec 2, 2011 at 19:35

Alastair's user avatar

4

Home / Ubuntu / Fix “username is not in the sudoers file” Error in Ubuntu

Fixing error – username is not in the sudoers file. this incident will be reported. Fix username is not in the sudoers file in Ubuntu or Debian.

Reason for the error “Username is not in the sudoers file. This error is reported in Ubuntu when:

  1. The permission on /etc/sudoers file is not set to 0440.
  2. User is not in sudo or admin group
  3. sudo Privileges error

1. Fixing Sudo Error Using Grub

At first, you need to restart your PC or laptop. You need to press the Shift key immediately for a few seconds to get the Grub boot menu. If you are using Ubuntu then You need to select “Advanced options for Ubuntu” and press Enter. In the next window, select the kernel with the “recovery mode” option and press Enter to advance to the “Recovery menu”. In the next window, you need to select “root Drop to root shell prompt”, then hit Enter.

Next, press Enter for maintenance. Now run the following command in the shell mode to change filesystem mode to read/write from read only mode.

read/write by running the command below:

sudo mount -o rw,remount /

Now add user to sudo or admin group. Run the following command to add the user to the sudo or admin group.

sudo adduser user_name sudo

After adding the user to the suo or admin group, grant sudo privileges to users. Open the sudoers file using the command

sudo visudo

and add the following content in the 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

Now set the correct permission on sudoers file using the following command to set the permission on sudoers file to 0440.

sudo chmod 0440 /etc/sudoers

Now, exit from the “Recovery menu” and reboot your Ubuntu System.

2. Fixing Sudo Error Using /etc/sudoers

Open file

sudo nano /etc/sudoers

Then add the user below admin user like below syntax.

user_name ALL=(ALL) ALL

Понравилась статья? Поделить с друзьями:
  • Is not a valid date как исправить
  • Is not a function javascript как исправить
  • Is not a debian format archive как исправить
  • Is not a block device ошибка монтирования
  • Is mf03 5 ошибка при удалении