Etc sudoers syntax error near line 30

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

20 Jun 2019Заметки

9619

~ 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

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 »

Сентябрь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.

Понравилась статья? Поделить с друзьями:
  • Etc error nissan leaf
  • Etc 961 ошибка е1
  • Etacs system error
  • Esxi проверить диск на ошибки
  • Esxi memory size error