Etc sudoers ошибка синтаксиса near line 31

I made the following change in the file /etc/sudoers:

sudo  ALL=(ALL) NOPASSWD:ALL

And now I can’t use sudo and can’t edit /etc/sudoers anymore:

/etc/sudoers: near line syntax error 31 <<<
sudo: parsing error in /etc/sudoers near line 31
sudo: no valid sudoers source found; going out
sudo: unable to initialize policy plugin

Is there a way to solve this problem or will I have to format my ubuntu 20.04?

  • sudo
  • etc

asked Feb 4, 2022 at 19:52

searcher__dm01's user avatar

4

  • If you can boot from a USB, you could mount the disk, find the ‘bad’ file and edit the line so that it reads correctly. I would eliminate the new line, and in the future, I would use sudo visudo to edit the file: you can also do sudo visudo -f /path/to/file when fixing your current file.

    Feb 4, 2022 at 20:00

  • The first error in the /etc/sudoers file becomes the EOF (end-of-file) marker; which is why the visudo command exists; ie. it will validate for errors & let you correct before exit if error(s) exist. FYI: yeah it’s visudo but it will use whatever editor you’ve told it to, which may not be vi

    Feb 4, 2022 at 21:06

  • This problem is why one Always has a root shell open on another tetminal/ssh session when one is futzing with authentication stuff. This gives one a chance of recovery without booting from a Live USB.

    Feb 4, 2022 at 23:21

Так или иначе, когда-нибудь нам сужденно столкнуться с правкой файла /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

Содержание

  1. Поврежденный /etc/sudoers — ошибка в синтаксисе
  2. Feanor184.ru
  3. SysAdmin-s notepad. DoFollow.
  4. Устраняем ошибку неправильного редактирования файла sudoers в Linux
  5. Для чего нужен sudoers?
  6. Что делать, если мы неправильно отредактировали файл?
  7. Справочная информация
  8. суббота, 14 апреля 2018 г.
  9. Ошибка синтаксиса sudoers
  10. 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?
  11. Short description
  12. Resolution
  13. Parse error in sudoers after giving sudo access without password

>>> /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 лет, постоянно учусь, люблю делать новые проекты.

Источник

Feanor184.ru

SysAdmin-s notepad. DoFollow.

Устраняем ошибку неправильного редактирования файла sudoers в Linux

Для чего нужен 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 а в этой строчке они неверно назначены. Тупиковая ситуация, если нет другого пользователя с правильными правами. Либо, копаем дальше.
Специально для данной ситуации, в линуксе есть команда:
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

Источник

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

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

суббота, 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, так как всегда сможете вернуться к корректному состоянию его содержания.

Источник

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.

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.

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

Amazon Linux, Ubuntu, and Debian:

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

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.

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.

Copy the file to the instance.

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

17. Attach the volume to the original instance. Specify the mount point as /dev/xvda or /dev/sda1, as this is the root volume for the original instance.

18. Start the original instance.

19. Connect to the instance using SSH and try running sudo commands.

Источник

Parse error in sudoers after giving sudo access without password

I am making a desktop application for Linux that interacts with some Ubuntu system files. As such, during the end-user’s installation of my software, I need to generate a file in /etc/sudoers.d/ giving a number of scripts access to the system files without knowing the password. The user will input there password during the installation, but after that they shouldn’t have to. During the installation, they will run give-sudo.sh which contains the following lines of Bash code:

It is supposed to create a file called moss-priv , and append the lines necessary to make my scripts run without requiring a password. I have 8 scripts, so I append 8 lines of code. The echo commands work fine, moss-priv is generated and its contents read:

This is when the issue occurs. Instead of giving password-less sudo to the scripts, it prints a stack trace saying an error occurred at each line (1-8). Not only that, but if I try to call sudo for any reason, it says «authorization failed» and stack traces. As such, I completely lost sudo access and couldn’t even go back to delete the file that was causing this issue. I ended up having to re-install the whole operating system just to get it back to normal.

Now that I have sudo back, I am ready to try it again as soon as I figure out what is wrong with the moss-priv file. I can’t figure it out though, I think it looks good. Help?

I would be happy with a solution to this problem or a good alternative method.

UPDATE: Going off of the suggested fixes, I have a file give_sudo.sh :

echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/power_off.sh» >> /etc/sudoers.d/moss-priv echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/reboot.sh» >> /etc/sudoers.d/moss-priv echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/timeout_moss.sh» >> /etc/sudoers.d/moss-priv echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/timeout_default.sh» >> /etc/sudoers.d/moss-priv echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/set_next_os.sh» >> /etc/sudoers.d/moss-priv echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/boot_os_1.sh» >> /etc/sudoers.d/moss-priv echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/boot_os_2.sh» >> /etc/sudoers.d/moss-priv echo «$SUDO_USER ALL=(ALL) NOPASSWD: /home/jeremiahdgage/Desktop/MOSS/give_sudo» >> /etc/sudoers.d/moss-priv

And one of the scripts, say timeout_moss.sh :

sudo sed -i ‘s/GRUB_HIDDEN_TIMEOUT=10/GRUB_HIDDEN_TIMEOUT=0.01/g’ /etc/default/grub

Источник

I’m trying to create a post install script for Linux and I want to have the script edit the sudoers file so that users wont need to do sudo visudo and edit it manually.

In the script I have:

if [[ ! `sudo -l -U "$user" 2>&1 | grep "ALL"` ]]; then
    su -c "echo '$user ALL=(ALL) ALL' >> /etc/sudoers"
    su -c "echo '$user ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers"
fi

the problem with this is that when I sudo whoami after I run the script I get this output:

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

How do I do this without ruining my sudoers file?

EDIT:
As requested here is my sudoers file:

Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# 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

Mind that it is not possible to do cat /etc/sudoers after the script has run.

EDIT 2:
The solution is to define $user as user=$(whoami)

По неосторожности изменил файл /etc/sudoers. Теперь уже не могу получить админские права в системе. Выходит ошибка:

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

Пробовал получить права через pkexec visudo, но также выходит ошибка после ввода пароля пользователя:

polkit-agent-helper-1 error response to policykit daemon

Кто-нибудь сталкивался с такой проблемой и что мне делать?

RRS feed

  • Remove From My Forums
  • Question

  • Hello,

    I accidentally messed with visudo and locked myself out from sudo on an Ubuntu Virtual Machine. Isn’t there a way to edit that or reset using some automation script, rather than deleting and recreating the whole machine, as described in https://docs.microsoft.com/en-us/azure/virtual-machines/linux/troubleshoot-recovery-disks-portal, which
    looks a very hard way around?

    Thanks, Chris

All replies

  • Thank you for the helpful answer but nope, it didn’t fix my issue, I still got syntax error in /etc/sudoers and can’t sudo.

  • Could you share the syntax error along with screenshot.

    —————————————————————————————————

    Do click on «Mark as Answer» on the post that helps you, this can be beneficial to other community members

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

    I can’t upload images (yet) due to the forum policy. Anyway, any attempt to use sudo renders the error above.

    Obviously I can’t investigate the line 31 of the file as my users has no rights to it and … it cannot sudo :)

    I should have probably changed the root’s password to something I know and now I could use su, but it was to easy just to start messing around with sudo…

    Or perhaps is there away to change root password of an existing machine using Azure portal?

    Thanks, Chris

    • Edited by

      Thursday, September 21, 2017 8:00 AM

    • Proposed as answer by
      Nirushi J
      Thursday, September 21, 2017 8:00 AM
  • Thank you for valuable tips. My case is now solved.

    FYI, the recipes from
    https://docs.microsoft.com/en-us/azure/virtual-machines/linux/using-vmaccess-extension didn’t really help against the case of broken /etc/sudoers file, as you can’t reset root user password this way and newly created sudo users still could not sudo.

    BUT

    I followed the links to the reference of Azure CLI and managed to fix my case using this:

    az vm run-command invoke -g <res> -n <vm> --command-id RunShellScript --scripts "..."

    For example you can copy and move files between locations on the target machine and change their permissions.  Well, you can do basically anything with this, because those —scripts are apparently run in the root context on the target machine. 
    Hurray for Azure.

    Thank you guys for your help!

  • Awesome :)Glad
    to know issue got resolved and Thank you for sharing the information as this might help other users.

    ——————————————————————————————
    Do click on «Mark as Answer» on the post that helps you, this can be beneficial to other community members

  • Yep. Any problem with sudoers should by solvable by

    az login
    az vm run-command invoke -g <res> -n <vm> --command-id RunShellScript --scripts "chmod 446 /etc/sudoers"
    <log in as regular user and edit /etc/sudoers out>
    az vm run-command invoke -g <res> -n <vm> --command-id RunShellScript --scripts "chmod 440 /etc/sudoers"

    I think it’s useful as there are other threads on this forum that advise reinstantiating the virtual machine. I reckon this is much cheaper way, at least for simple cases as mine.

    • Edited by
      Krzysztof Nosek
      Saturday, October 14, 2017 11:08 AM

  • Etamatic oem коды ошибок
  • Etacs mitsubishi pajero 4 ошибка
  • Esxi базовое соединение закрыто непредвиденная ошибка при передаче
  • Est 37 коды ошибок
  • Esr ошибка на авто