Sudo parse error in etc sudoers near line

I am getting this error: sudo: parse error in /etc/sudoers near line 23 sudo: no valid sudoers sources found, quitting sudo: unable to initialize policy plugin I was trying to disable password

I am getting this error:

sudo: parse error in /etc/sudoers near line 23
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

I was trying to disable password authentication so I don’t have to type password every time I want to install something, but I probably changed it in a not very good way.
I am a newbie to Ubuntu, I got sick of Windows :)

So far I’ve found some people suggesting booting in single user mode, but I’m afraid of messing things up more.

How can I fix this error?

Alaa Ali's user avatar

Alaa Ali

30.5k11 gold badges93 silver badges105 bronze badges

asked Oct 30, 2012 at 11:06

Robert Fáber's user avatar

13

Fixing this is dead simple, and it is answered elsewhere on askubuntu.

Short answer, use:

pkexec editor_of_choice

Community's user avatar

answered Nov 25, 2015 at 9:39

NeilenMarais's user avatar

5

Hold Shift immediately while booting so that you get the GRUB screen. Select the recovery mode. Choose to drop to a root terminal. Run mount -n -o remount,rw / and then visudo. It’ll let you fix your problems with the file and save. It won’t let you save a malformed file.

answered Oct 30, 2012 at 12:41

nanofarad's user avatar

nanofaradnanofarad

20.5k12 gold badges63 silver badges90 bronze badges

5

Folowing solution is for remote servers, it works!

http://ubuntuforums.org/showthread.php?t=2036382&p=12144840#post12144840

then just use visudo to add wheel, etc


  1. Rename your current file

    mv /etc/sudoers{,.bak}

  2. Create a new one vi /etc/sudoers with the following basic content:

    # /etc/sudoers
    #
    # This file MUST be edited with the 'visudo' command as root.
    #
    # See the man page for details on how to write a sudoers file.
    # Defaults    env_reset
    # Host alias specification
    # User alias specification
    # Cmnd alias specification
    # User privilege specification
    root    ALL=(ALL) ALL
    # Allow members of group sudo to execute any command after they have
    # provided their password
    # (Note that later entries override this, so you might need to move
    # it further down)
    %sudo ALL=(ALL) ALL
    #
    #includedir /etc/sudoers.d
    # Members of the admin group may gain root privileges
    %admin ALL=(ALL) ALL
    
  3. Run visudo and add your custom stuff.

Kevin Bowen's user avatar

Kevin Bowen

19.2k55 gold badges75 silver badges81 bronze badges

answered Sep 15, 2013 at 1:09

Igor Parra's user avatar

Igor ParraIgor Parra

2091 silver badge5 bronze badges

1

If u messed up your sudoers file.You’ll need to:

  • Reboot into recovery mode (hit escape during boot, choose the recovery mode option on the grub screen)
  • Choose the ‘Enable networking’ option (if you don’t your filesystem will be mounted as read-only. who knew)
  • Chosee the ‘Drop to root shell’ option
  • run visudo, fix your file
  • Reboot with normal grub option

source :- http://mario.net.au/content/recover-etcsudoers-ubuntu-1204

answered Dec 14, 2012 at 11:03

streak's user avatar

streakstreak

2492 silver badges5 bronze badges

1

You can do this:

Create a copy

cp /etc/sudoers /etc/sudoers.bak

Edit problem parts there

vim /etc/sudoers.bak

Replace the origin sudoers file

cp /etc/sudoers.bak /etc/sudoers

It works for me.

answered Jul 3, 2014 at 9:41

ajile's user avatar

ajileajile

1444 bronze badges

2

I screwed up the sudoers file to find out that I don’t remember the root password. Solution: rebooted under Windows (I have a dual boot) and edited the file using ext2fsd (you have to reboot after the installation). In principle, this could be another Linux or a live flash, not necessarily Windows.

answered Jul 1, 2015 at 15:22

18446744073709551615's user avatar

1

Содержание

  1. Поврежденный /etc/sudoers — ошибка в синтаксисе
  2. [РЕШЕНО] Поврежденный /etc/sudoers — ошибка в синтаксисе
  3. Как исправить повреждённый файла sudoers
  4. Sudoers
  5. How to modify an invalid ‘/etc/sudoers’ file?
  6. 17 Answers 17
  7. Справочная информация
  8. суббота, 14 апреля 2018 г.
  9. Ошибка синтаксиса sudoers

Поврежденный /etc/sudoers — ошибка в синтаксисе

>>> /etc/sudoers: ошибка синтаксиса near line

Так или иначе, когда-нибудь нам сужденно столкнуться с правкой файла /etc/sudoers . и не всегда редактирование заканчивается успешно, если ты такой же «удачливый» гоу под спойлер

Обычная ситуация, вам нужно подредактировать права суперпользователя, в файле /etc/sudoers. Но никто не застрахован от ошибок, и я снова наступил на те же грабли спустя год, вместо команды sudo visudo я отредактировал файл с помощью стандартного sudo nano /etc/sudoers и после сохранения всех правок и попытке использовать права суперпользователя, система выдала ошибку:

Синтаксис еррор, короче повредил синтаксис файла своими кривыми ручонками.

Есть достаточно тривиальный способ решения проблемы, использовать:

Пуфффф. И вопрос с редактированием /etc/sudoers решится сам собой. А если потребуется отредактировать файлы в директории /etc/sudoers.d/ то можно ввести:

Но в этот раз что-то пошло не так, и я получил в ответ:

Интересная ситуация, чтобы редактировать sudoers мне нужны права суперпользователя, но получить я их могу, только «починив» файл sudoers — замкнутый круг. Но есть гениальный выход из этой ситуации:

Откройте два сеанса ssh к серваку (или работа в двух терминалах или две вкладки в терминале, я использую Guake Terminal ).

В первом сеансе получите PID bash:

Во второй сессии запустите агент аутентификации с помощью:

Вернувшись в первый сеанс, запустите:

На втором сеансе вы получите приглашение пароля:

visudo запуститься в первой сессии.

Туда-сюда, туда-сюда и проблема решена! Ну и напоследок совет, при правках используйте sudo visudo, т.к. он проверяет синтаксис перед сохранением файла, и если что-то пойдет не так, то выдаст предупреждение:

Веб-разработчик со стажем программирования более 13 лет, постоянно учусь, люблю делать новые проекты.

Источник

[РЕШЕНО] Поврежденный /etc/sudoers — ошибка в синтаксисе

Так или иначе, когда-нибудь нам суждено столкнуться с правкой файла /etc/sudoers …и не всегда редактирование заканчивается успешно, если ты такой же «удачливый» как и Я, то ты пришел по адресу.

Обычная ситуация, вам нужно что-то подкорректировать в файле /etc/sudoers. Но как говориться: «Никто не застрахован от ошибок», и я тут не исключение. Вместо команды sudo visudo я отредактировал файл с помощью стандартного sudo nano /etc/sudoers и после сохранения всех правок и попытке использовать права суперпользователя, система выдала ошибку:

Что тут сказать, повредил синтаксис файла sudoers .

Все попытки открыть файл на редактирование заканчивается неудачей.

Скажу больше, после редактирования данного файла, вообще нет возможности войти под root пользователем, т.к. sudo теперь тоже не работает.

Как исправить повреждённый файла sudoers

Способ решение в сложившейся проблемы достаточно тривиальный, надо использовать:

Пуфффф…И вопрос с редактированием /etc/sudoers решится сам собой. А если потребуется отредактировать файлы в директории /etc/sudoers.d/ то можно ввести:

Но в этот раз что-то пошло не так, и я получил в ответ:

Интересная ситуация, чтобы редактировать sudoers мне нужны права суперпользователя, но получить я их могу, только «починив» файл sudoers — замкнутый круг.

Но есть гениальный выход из этой ситуации:

Откройте два сеанса ssh к серваку (или работа в двух терминалах или две вкладки в терминале).

В первом сеансе получим PID bash вашей сессии:

Во второй запустите агент аутентификации с помощью:

Вернувшись в первый сеанс, запустите:

На втором сеансе вы получите приглашение пароля:

visudo запуститься в первой сессии.

Туда-сюда, туда-сюда и проблема решена! Ну и напоследок совет, при правках используйте sudo visudo, т.к. он проверяет синтаксис перед сохранением файла, и если что-то пойдет не так, то выдаст предупреждение:

Если есть вопросы, то пишем в комментариях.

Также можете вступить в Телеграм канал, ВКонтакте или подписаться на Twitter. Ссылки в шапке страницы.
Заранее всем спасибо.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Сегодня в статье настроим и русифицируем Ubuntu Server 16.04/18.04/20.04. Чтобы поддерживался русский язык, и перевод системы стал русским

Начиная с сентября 2017 года удостоверяющим центрам предписано обязательно проверять CAA-записи в DNS перед генерацией сертификата

В этой статье рассмотрим пример обновления Ubuntu Server 16.04 до Ubuntu Server 18.04 Все наши действия нам придется выполнять из Читать

В связи с последними блокировками IP-адресов Роскомнадзором, встала необходимость завести свой собственный VPN сервер. Если VPN у вас ещё не Читать

Источник

Sudoers

Недавно прешёл на Debian и учась установке программ в линуксе вычитал и изменил файл Sudoers и теперь терменал выдает: «sudo: parse error in /etc/sudoers near line 8 sudo: no valid sudoers sources found, quitting sudo: не удаётся инициализировать модуль политики» Подскажите как вернуть всё на место?

сделай cat /etc/sudoers и покажи его сюда

Надо было через visudo редактировать его.

Вот как он выглядит.

# This file MUST be edited with the ‘visudo’ command as root. # # See the man page for details on how to write a sudoers file. #

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

поставь перенос строки после 32-го пробела.

первый раз про это слышу) всегда руками правил и не ломал)

дебиан, в основном

«Ну зачем, зачем ты туда полез? Тебе что делать нечего?»

В дебиане же всё настроено, остаётся только добавить нужных пользователей в группу sudo: # usermod -a -G sudo $username

мне проще скокпипастить строчку рута в sudoers и поменять на нужный юзернейм

А почему ты тогда sudoers не dd правишь? Куда еще проще?

Тебе проще ввести эту команду, подставив нужного пользователя.

поставь себе stardict/qstardict/goldendict/google.translate.com etc, используй мозг и т. п.

вычитал и изменил файл Sudoers и теперь терменал выдает

Никогда не редактируй sudoers вручную!

А так же напомню о main vipw и man vigr . А то вдруг ты их тоже вручную редактировать станешь.

Нет, ну можно конечно. Но зачем устраивать себе пикник на минном поле?

Странный у тебя дебиан

первый раз про это слышу) всегда руками правил и не ломал)

Люди делятся на тех, кто ещё не делает бекапы и тех, кто уже делает бекапы редактирует sudoers в ручную или как положено.

Никогда не редактируй sudoers вручную!

Это еще почему? Все нормально редактируется. visudo рекомендуется использовать по вполне определенной причине, которая далеко не во всех случаях актуальна.

visudo edits the sudoers file in a safe fashion, analogous to vipw(8). visudo locks the sudoers file against multiple simultaneous edits, provides basic sanity checks, and checks for parse errors.

Огромного смысла нет. Особенно на однопользовательской машине.

звучит как «всегда стрелял себе в ногу, ни разу не попадал» 🙂

Сам же ведь и ответил:

provides basic sanity checks, and checks for parse errors

Т.е. исключает возможность запороть конфиг и остаться у разбитого корыта.

Т.е. исключает возможность запороть конфиг и остаться у разбитого корыта.

А чем так опасен запоротый конфиг на локальной машине? У меня права root. Я зайду снова и поправлю. Я отмечаю как раз случай однопользвательской машины. Если пользователей много, машина в общем доступе, то уже можно обсуждать, так как синтаксическая ошибка моментально скажется на работе всех моментально.

Если ты запоришь passwd, то и root’ом может быть не зайдёшь.

А на убунте и root’а то нет. Только sudo. И тут уже 4 файла, которые нельзя ломать (passwd, shadow, groups, sudoers).

Нет, можно конечно уйти в single-user / liveCD / whatever и поправить. Но зачем? Если уже есть тулза, которая такие промахи исключает?

чё вы так все боитесь править этот файл? обычный конфиг, такой же как и все) если налажать (не знаю как мне лично надо напиться чтобы налажать в таком конфиге), то можно зайти под рутом со своим паролем, и тупо отредактировать его как надо, или загрузиться с лив-сиди, как уже подсказали

это касается всех конфигов, в которых внутри написано «ололо, не править!», типа resolv и им подобных. поправлю, и еще навешаю атрибут i, ибо я должен решать, что системе делать, а не она мне указывать.

можно конечно добавлять юзера в группу через ту команду с ключами, сиди и запоминай их ещё, ага. ещё можно тупо править /etc/groups

Источник

How to modify an invalid ‘/etc/sudoers’ file?

How do I edit an invalid sudoers file? It throws the below error and it’s not allowing me to edit again to fix it.

Here is what happens:

17 Answers 17

On a modern Ubuntu system (and many other GNU/Linux distributions), fixing a corrupted sudoers file is actually quite easy, and doesn’t require rebooting, using a live CD, or physical access to the machine.

To do this via SSH, log in to the machine and run the command pkexec visudo . If you have physical access to the machine, SSH is unnecessary; just open a Terminal window and run that pkexec command.

Assuming you (or some other user) are authorized to run programs as root with PolicyKit, you can enter your password, and then it will run visudo as root , and you can fix your /etc/sudoers .

If you need to edit one of the configuration files in /etc/sudoers.d (which is uncommon in this situation, but possible), use pkexec visudo -f /etc/sudoers.d/filename .

If you have a related situation where you have to perform additional system administration commands as root to fix the problem (also uncommon in this circumstance, but common in others), you can start an interactive root shell with pkexec bash . Generally speaking, any non-graphical command you’d run with sudo can be run with pkexec instead.

(If there is more than one user account on the system authorized to run programs as root with PolicyKit, then for any of those actions, you’ll be asked to select which one you want to use, before being asked for your password.)

If that doesn’t work—for example, if there are no users authorized to run programs as root via PolicyKit—then boot from an Ubuntu live CD (like the CD you probably used to install Ubuntu) and mount the filesystem for the installed system. You can do this by running sudo parted -l to view your partitions—there is probably just one ext4 partition, and that’s the root filesystem.

Suppose the installed Ubuntu system’s root filesystem is on /dev/sda1 . Then you could mount it with sudo mount /dev/sda1 /mnt . Then you can edit the installed system’s sudoers file with sudo nano -w /mnt/etc/sudoers . Or, even better, you can edit it with

(which will prevent you from saving a sudoers file with incorrect syntax).

Источник

Справочная информация

про свой опыт решения некоторых проблем и использования ряда возможностей ОС и приложений

суббота, 14 апреля 2018 г.

Ошибка синтаксиса sudoers

При попытке настроить срабатывание одного из скриптов, который обращается к системной функции от имени обычного пользователя системы, возникла необходимость внести изменения в полномочия пользователя через файл /etc/sudoers

В найденных на эту тему материалах говорится, что редактирование данного файла необходимо производить через команду visudo . Хотелось бы, конечно, чтобы авторы таких материалов уточняли, что команду следует запускать от имени суперпользователя, так как при вводе просто visudo в терминале появляется:

$ visudo
visudo: /etc/sudoers: Отказано в доступе

После ввода «правильной» команды открывается окно редактора nano с загруженным в него содержанием файла sudoers .

Авторы публикаций поясняют, что при таком способе будет проверяться правильность синтаксиса вносимых в него изменений.

Вследствие отсутствия необходимости использования редактора nano мне не было известно назначение клавиш, с помощью которых производится запись в файл вносимых изменений:

И только в дальнейшем после «подсказки друга» мне стало известно, что символ ^ соответствует клавише Ctrl.

Поэтому редактирование мной файла sudoers производилось более привычным способом – sudo gedit /etc/sudoers

Увы, никто не застрахован от ошибок и после очередного эксперимента с редактированием содержания этого файла система мне выдала сообщение:

>>> /etc/sudoers: ошибка синтаксиса near line 21 pkexec visudo

После ввода пароля суперпользователя будет открыт тот же редактор nano с загруженным в него содержанием файла sudoers .

Соотнесите содержание своего файла с содержанием по умолчанию (без строк, начинающихся с символа комментария #):

root ALL=(ALL:ALL) ALL
%admin ALL=(ALL) ALL
%sudo ALL=(ALL:ALL) ALL

Исправьте свои «неверные» записи или приведите файл к исходного значению, после чего нажмите на комбинацию клавиш Ctrl и o. На последующий запрос нажмите y:

Далее, используя клавишу Backspace, удалите в наименовании файла .tmp и на вопрос о перезаписи существующего файла снова нажмите клавишу y:

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

Источник

Problem

Patch upgrade fails to run due to bad characters in the /etc/sudoers file.

Symptom

Immediately after running the patch upgrade, the following message is displayed:

sudo: parse error in /etc/sudoers near line xxx
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

Cause

As QRadar® does not use sudoers by default, manual edits in the /etc/sudoers in the appliances might cause this issue when a bad-formatted text is added.

Additionally, manually copying text from Windows® to Linux® might result in the end of line characters being added.  Refer to Adding custom actions to learn how to use the dos2unix command.

Environment

QRadar® Appliances with Linux sudoers customizations.

Diagnosing The Problem

  1. Take note of the line reported in the error.
    sudo: parse error in /etc/sudoers near line 122
    sudo: no valid sudoers sources found, quitting
    sudo: unable to initialize policy plugin
  2. Go to the line that displays the error by using the cat command.
    cat -An /etc/sudoers | grep 122 -B 4 -A 10
    122  Cmnd_Alias IBM_UNIX_PIM_CMDS = /usr/bin/passwd,/usr/sbin/useradd, $
    123  M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  /usr/sbin/usermod,/usr/sbin/userdel,/usr/bin/tee,/bin/chmod, $
    124  M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  /bin/cat,/bin/ls,/usr/bin/chage,/usr/bin/groups,/bin/ed, $
    125  M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  /bin/cp,/usr/bin/faillog,/usr/sbin/groupadd,/usr/sbin/groupmod, $
    126  M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  /usr/sbin/groupdel,/usr/bin/kill,/bin/hostname,/sbin/faillock, $
    127  M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  /sbin/pam_tally2,/bin/mkdir,/bin/rm,/usr/bin/lastlog,/sbin/faillog, $
    128  M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  /usr/bin/psql,/usr/bin/pg_dump,/usr/bin/htpasswd,/opt/qradar/ha/bin/ha_getstate.sh,$
    129  M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  /opt/qradar/support/changePasswd.sh$
    130  $
    131  mspipat1M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  ALL=NOPASSWD:IBM_UNIX_AE_BAU_CMDS$
    132  svcmssM-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM- M-BM-  ALL=NOPASSWD:IBM_UNIX_PIM_CMDS$
    133  $

In the previous output, the characters M-BM-indicate a bad-formatted text. A well-formatted text would look as the following:

122  Cmnd_Alias IBM_UNIX_PIM_CMDS = /usr/bin/passwd,/usr/sbin/useradd, $
123                  /usr/sbin/usermod,/usr/sbin/userdel,/usr/bin/tee,/bin/chmod, $
124                  /bin/cat,/bin/ls,/usr/bin/chage,/usr/bin/groups,/bin/ed, $
125                  /bin/cp,/usr/bin/faillog,/usr/sbin/groupadd,/usr/sbin/groupmod, $
126                  /usr/sbin/groupdel,/usr/bin/kill,/bin/hostname,/sbin/faillock, $
127                  /sbin/pam_tally2,/bin/mkdir,/bin/rm,/usr/bin/lastlog,/sbin/faillog, $
128                  /usr/bin/psql,/usr/bin/pg_dump,/usr/bin/htpasswd,/opt/qradar/ha/bin/ha_getstate.sh,$
129                  /opt/qradar/support/changePasswd.sh$
130 $
131 mspipat1        ALL=NOPASSWD:IBM_UNIX_AE_BAU_CMDS$
132 svcmss          ALL=NOPASSWD:IBM_UNIX_PIM_CMDS$
133 $

Resolving The Problem

To resolve this issue, administrators must either remove the bad-formatted characters lines or replace the lines with well formatted lines in the /etc/sudoers file.

Note: The following steps use the line numbers reported in the Diagnosing the Problem section in this technote. The administrator must change the commands according to their environment.

Remove bad-formatted text procedure

  1. Log in to the appliance by using SSH, XCC, or equivalent as the root user.
  2. Delete the lines containing the bad-formatted text by using the sed command.
    1. Create a backup directory and backup the existing file.
      mkdir -p /store/IBM_Support
      cp -pfv /etc/sudoers /store/IBM_Support/
    2. Delete the conflicting lines.
      Note: In this technote, the conflicting lines start at line 122 until line 132. The following command deletes all those lines at once.

      sed -i '122,132d' /etc/sudoers
  3. Rerun the patch.
    /media/updates/installer

Replace bad-formatted text procedure

Note: To run this procedure, there must exist another appliance with an equivalent text to the one affected. Additionally, knowledge about the vim command is required.

  1. Gather the right output from another appliance that is not affected by this issue.
    1. Log in to the appliance by using SSH, XCC, or equivalent as the root user.
    2. Verify the content to be copied is well-formatted (see the Diagnosing the Problem section).
      cat -A /etc/sudoers
    3. Create a backup directory and backup the existing file.
      mkdir -p /store/IBM_Support
      cp -pfv /etc/sudoers /store/IBM_Support/
    4. Copy the content of the lines required using the cat command.
      cat /etc/sudoers
  2. Copy the previous gathered content and replace it in the /etc/sudoers on the affected appliance.
    1. Log in to the appliance by using SSH, XCC, or equivalent as the root user.
    2. Remove and replace the content of the conflicting lines by using the vim command.
      1. Go to the conflicting line (see the Diagnosing the Problem section).
        vim +122 /etc/sudoers
      2. Press ESC to ensure vim is on Normal Mode.
      3. Type :set nu to print the line information in the file.
      4. Navigate through the lines using the arrow keys on the keyboard.
      5. Remove each of the lines by pressing dd.
      6. Paste the well-formatted lines in their corresponding line (previously gathered in step 1).
      7. Save and exit the vim editor by pressing :wq
  3. Rerun the patch
    /media/updates/installer

Result:

The patch screen must start successfully.

Document Location

Worldwide

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.

[{«Type»:»SW»,»Line of Business»:{«code»:»LOB24″,»label»:»Security Software»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Product»:{«code»:»SSBQAC»,»label»:»IBM Security QRadar SIEM»},»ARM Category»:[{«code»:»a8m0z000000cwtdAAA»,»label»:»Upgrade»}],»ARM Case Number»:»TS005544221″,»Platform»:[{«code»:»PF016″,»label»:»Linux»}],»Version»:»All Version(s)»}]

I edited the sudoers file on my EC2 instance and now I’m receiving syntax errors when trying to run sudo commands. How do I fix this?

Last updated: 2021-09-17

I manually edited the sudoers file on my Amazon Elastic Compute Cloud (Amazon EC2 instance). Now I’m receiving a syntax error similar to the following when trying to run sudo su commands or commands that require privileged user access:

  • «/etc/sudoers: syntax error near line xx»
  • «sudo: parse error in /etc/sudoers near line xx»
  • «sudo: no valid sudoers sources found, quitting»
  • «sudo: unable to initialize policy plugin»

Short description

This syntax error occurs when the /etc/sudoers file is manually edited to change the sudo user and unwanted characters are added to the file. The result can be an impaired instance that can’t run sudo su or commands that require privileged user access. To fix this syntax error, stop the instance, detach its root volume, attach it to a recovery instance, mount the root volume as a secondary volume, and then revert the changes to the sudoers file.

Warning: Before starting this procedure, be aware of the following:

  • Stopping and restarting the instance erases any data on instance store volumes. Be sure that you back up any data on the instance store volume that you want to keep. For more information, see Determine the root vevice type of your instance.
  • Stopping and restarting the instance changes the public IP address of your instance. It’s a best practice to use an Elastic IP address instead of a public IP address when routing external traffic to your instance.

Resolution

Note: Don’t manually edit the sudoers file using a text editor such as vi, vim, or nano on a running instance that you can connect to. Always run visudo to edit the /etc/sudoers file on instances that you can connect to. Visudo checks for parse errors as you edit so that any issues introduced into the file are brought to your attention before you save the changes.

1.    Open the Amazon EC2 console.

2.    Choose Instances from the navigation pane, and then select the impaired instance.

3.    Choose Actions, choose Instance State, and then choose Stop.

4.    In the Description tab, select the Root device, and then select the EBS ID.

5.    Choose Actions, choose Detach Volume (/dev/sda1 or /dev/xvda), and then choose Yes, Detach.

6.    Verify that the State is Available.

7.    Launch a new EC2 instance in same Availability Zone as the original instance. The new instance becomes your rescue instance.

8.    After the rescue instance launches, choose Volumes from the navigation pane, and then select the detached root volume of the original instance.

9.    Choose Actions, and then choose Attach Volume.

10.    Select the rescue instance ID (1-xxxx) and then enter a device name (/dev/sdf, for example).

11.    Use SSH to connect into the rescue instance using your key pair.

12.    Run the lsblk command to verify the device name of the attached volume.

The following is an example of the output.

NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
xvda    202:0    0    8G  0 disk
└─xvda1 202:1    0    8G  0 part /
xvdf    202:80   0  500G  0 disk
└─xvdf1 202:81   0  500G  0 part

13.    Create a mount directory and then mount with root privileges:

Amazon Linux, Ubuntu, and Debian:

sudo mount /dev/xvdf1 /mnt

Amazon Linux 2, CentOS 7 or 8, SUSE Linux 12, and RHEL 7.x or 8.x:

sudo mount -o nouuid /dev/xvdf1 /mnt

Check the mount point in the console for the newly attached volume. Usually that mount point is /dev/xvdf1.

14.    Chroot into the mounted directory.

for dir in {/dev,/dev/pts,/sys,/proc}; do sudo mount -o bind $dir /mnt$dir; done
chroot /mnt

15.    Edit the sudoers file using visudo command.

There are two options for editing the file:

Option 1: Revert the changes you made that created the syntax error.

Option 2: Replace the /mnt/etc/sudoers file with a known correct file from the recovery instance by copying the file from the recovery instance.

Create a backup of the original file.

sudo mv /mnt/etc/sudoers /mnt/etc/sudoers.backup

Copy the file to the instance.

sudo cp /etc/sudoers /mnt/etc/sudoers

16.    After you edit or replace the sudoers file, unmount the volume.

for dir in {/dev,/dev/pts,/sys,/proc}; do umount /mnt$dir; done
sudo umount /mnt


Did this article help? 


Do you need billing or technical support?

AWS support for Internet Explorer ends on 07/31/2022. Supported browsers are Chrome, Firefox, Edge, and Safari.
Learn more »

20 Jun 2019Заметки

9643

~ 2 мин.

Так или иначе, когда-нибудь нам сужденно столкнуться с правкой файла /etc/sudoers …и не всегда редактирование заканчивается успешно, если ты такой же «удачливый» гоу под спойлер

Обычная ситуация, вам нужно подредактировать права суперпользователя, в файле /etc/sudoers. Но никто не застрахован от ошибок, и я снова наступил на те же грабли спустя год, вместо команды sudo visudo я отредактировал файл с помощью стандартного sudo nano /etc/sudoers и после сохранения всех правок и попытке использовать права  суперпользователя, система выдала ошибку:

>>> /etc/sudoers: syntax error near line 23 <<<
sudo: parse error in /etc/sudoers near line 23
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

Синтаксис еррор, короче повредил синтаксис файла своими кривыми ручонками.

Есть достаточно тривиальный способ решения проблемы, использовать:

pkexec visudo

Пуфффф…И вопрос с редактированием /etc/sudoers решится сам собой. А если потребуется отредактировать файлы в директории /etc/sudoers.d/ то можно ввести:

pkexec visudo -f /etc/sudoers.d/<file_name>

ПРОФИТ!

Но в этот раз что-то пошло не так, и я получил в ответ:

==== AUTHENTICATING FOR org.freedesktop.policykit.exec ===
Authentication is needed to run `/usr/sbin/visudo' as the super user
Authenticating as: user,,, (name) Password: polkit-agent-helper-1:
error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie
==== AUTHENTICATION FAILED ===
Error executing command as another user: Not authorized
This incident has been reported.

Интересная ситуация, чтобы редактировать sudoers мне нужны права суперпользователя, но получить я их могу, только «починив» файл sudoers — замкнутый круг. Но есть гениальный выход из этой ситуации:

Откройте два сеанса ssh к серваку (или работа в двух терминалах или две вкладки в терминале, я использую Guake Terminal ).

В первом сеансе получите PID bash:

echo $$

Во второй сессии запустите агент аутентификации с помощью:

#PID - полученный идентификатор процесса 
pkttyagent --process PID

Вернувшись в первый сеанс, запустите:

pkexec visudo

На втором сеансе вы получите приглашение пароля:

==== AUTHENTICATING FOR org.freedesktop.policykit.exec ===
Для запуска приложения `/usr/sbin/visudo' от имени суперпользователя требуется аутентификация
Authenticating as: user,,, (name)
Password:
==== AUTHENTICATION COMPLETE ===

visudo запуститься в первой сессии. 

Туда-сюда, туда-сюда и проблема решена! Ну и напоследок совет, при правках используйте sudo visudo, т.к. он проверяет синтаксис перед сохранением файла, и если что-то пойдет не так, то выдаст предупреждение:

>>> /etc/sudoers: syntax error near line 30 <<<
What now? #Что будем делать?
Options are:
(e)dit sudoers file again #снова редактировать
e(x)it without saving changes to sudoers file #выйти без сохранения
(Q)uit and save changes to sudoers file (DANGER!) #сохранить изменения (3,14здец!)
What now? x

Сентябрь21

LinuxВ Linux есть довольно много системных файлов,  бездумное и неаккуратное редактирование которых может привести к неправильной работе системы или даже, в некоторых случаях, к kernel crash dump. Пути решения проблемы для каждого конкретного случая буду своими. В данной статье будет рассмотрено, что делать, если вы неправильно отредактировали файл sudoers.

Для чего нужен sudoers?

Файл лежит в директории /etc/ и определяет наличие или отсутствие у пользователей прав выполнять команды от имени супер администратора — командой sudo. Так же он отвечает за некоторые приятные мелочи, вроде возможности отключить ввод пароля для команды sudo каждый раз при ее выполнении.

Дефолтный файл будет содержать примерно следующие строки:
# 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

 Что делать, если мы неправильно отредактировали файл?

Допустим, я хочу добавить в это файл пользователя feanor184 и разрешить ему выполнять sudo без ввода пароля. Я дописываю:
# User privilege specification
root ALL=(ALL:ALL) ALL
feanor184 ALL=(ALL:ALL) no password: ALL

и сохраняю файл.

Желаемый результат я не получил. Связано это с тем, что я неправильно указал синтаксис. Вместо «no password: ALL» нужно было написать «NOPASSWD: ALL«. Казалось бы, какая проблема? Сейчас зайдем и поменяем)
Но не тут то было…теперь при попытке открытия файла мне будет выдаваться ошибка:
feanor184@home:~$ sudo vim /etc/sudoers
>>> /etc/sudoers: syntax error near line 21 <<<
sudo: parse error in /etc/sudoers near line 21
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

файл для своего открытия требует права sudo а в этой строчке они неверно назначены. Тупиковая ситуация, если нет другого пользователя с правильными правами. Либо, копаем дальше.
Специально для данной ситуации, в линуксе есть команда:
feanor184@home:~$ pkexec visudo
==== AUTHENTICATING FOR org.freedesktop.policykit.exec ===
Authentication is needed to run `/usr/sbin/visudo' as the super user
Authenticating as: feanor184,,, (feanor184)
Password:
==== AUTHENTICATION COMPLETE ===
>>> /etc/sudoers: syntax error near line 21 <<<

Вводим свой пароль и исправляем:
# User privilege specification
root ALL=(ALL:ALL) ALL
feanor184 ALL=(ALL:ALL) NOPASSWD: ALL

Метки: linux, sudo
Copyright © 2013-2017. All rights reserved.

I’ve created a user called kafka to whom I am trying to give a sudo access to run only /etc/init.d/kafka commands.

I added the following entry to /etc/sudoers.d/kafka via Ansible:

kafka ALL = NOPASSWD: /etc/init.d/kafka

However, this breaks sudo completely with the following error:

/etc/sudoers.d/kafka: syntax error near line 1
sudo: parse error in /etc/sudoers.d/kafka near line 1
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

Here’s the full Ansible snippet:

- name: Create kafka user's group
  group:
    name: "{{ kafka_group }}"
    state: present

- name: Create kafka user
  user:
    name: "{{ kafka_user }}"
    state: present
    group: "{{ kafka_group }}"
    shell: /bin/bash

- name: Set up password-less sudo for kafka user
  copy:
    content: "{{ kafka_user }} ALL = NOPASSWD: /etc/init.d/{{ kafka_service_name }}"
    dest: "/etc/sudoers.d/{{ kafka_user }}"
    owner: root
    group: root
    mode: 0440

What am I doing wrong?

HBruijn's user avatar

HBruijn

73.5k23 gold badges132 silver badges194 bronze badges

asked Jul 26, 2016 at 6:29

jeffreyveon's user avatar

0

A «sudo: parse error in …» originating from /etc/sudoers or any of the files included with either the #include <filename> or #includedir <path> directives may be caused by a missing new-line on the last entry in that file.

answered Jul 26, 2016 at 6:53

HBruijn's user avatar

HBruijnHBruijn

73.5k23 gold badges132 silver badges194 bronze badges

Using the copy module is probably not the best choice to handle /etc/sudoers with Ansible.

The lineinfile module has an option to validate the file before saving. It is also easier to remove the line, etc with that module.

The documentation contains an example how to use it.

- name: Set up password-less sudo for kafka user
  lineinfile: dest=/etc/sudoers state=present regexp='^%{{ kafka_user }} ALL=' line='%{{ kafka_user }} ALL= NOPASSWD: /etc/init.d/{{ kafka_service_name }}' validate='visudo -cf %s'

answered Jul 27, 2016 at 10:12

Henrik Pingel's user avatar

Henrik PingelHenrik Pingel

8,8962 gold badges26 silver badges38 bronze badges

Понравилась статья? Поделить с друзьями:
  • Sudo apt update ошибка
  • Sudo apt install npm error
  • Sudo apt install gcc ошибка
  • Sudo apt get update error
  • Sudo a2enmod php error module php does not exist