最近登上远程主机时莫名报错sudo不能用了,原因是 /etc/sudoers.d/文件夹下有一个文件语法错误。搞了好几天,终于搞定了
这个错误的麻烦之处是这个文件必须使用sudo命令才可以修改,而sudo又不能用,所以只能干瞪眼着急。好在找到了一种骚套路解决方法,现在分享给大家!
>>> /etc/sudoers.d/50_stack_sh: syntax error near line 1 <<<
>>> /etc/sudoers.d/50_stack_sh: syntax error near line 2 <<<
>>> /etc/sudoers.d/50_stack_sh: syntax error near line 3 <<<
sudo: parse error in /etc/sudoers.d/50_stack_sh near line 1
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin
自此,无法使用sudo命令,无法打开/etc/sudoers文件,当然也无法修改/etc/sudoers文件。
解决
网上的解决方法是,用下列命令重新打开sudoers文件,从而把之前修改的地方恢复。
pkexec visudo
但是,这个命令执行后,需要输入密码进入root权限,但因为sudoers文件损坏,输入密码后出现下列错误:
==== AUTHENTICATING FOR org.freedesktop.policykit.exec ===
Authentication is needed to run `/usr/sbin/visudo' as the super user
Authenticating as: ubuntu,,, (ubuntu)
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.
这就尴尬了。最终的解决办法如下:
1、打开两个ssh终端,都是用同一个ubuntu用户登录
2、在第一个终端输入以下命令,获取pid
echo $$
3、在第二个终端,输入:
pkttyagent --process 刚刚得到的pid
4、这个时候,第二个终端会卡住,在第一个终端输入:
pkexec visudo
5、然后,第一个终端也卡主,回到第二个终端,会提示输入当前用户密码,输入
6、好吧,输入完密码,第二个终端卡主了,回到第一个终端,会发现,出现了sudoers的内容,编辑出错的地方,保存即可。
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults env_reset
Defaults mail_badpass
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/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
我的sudoer文件是这样的,可以看到最下方莫名其妙多出现了两行
# See sudoers(5) for more information on "#include" directives:
#includedir /etc/sudoers.d
将这两行删去,保存退出,就可以发现sudo可以正常使用了~
7、完成任务,修改完成,发现就可以继续使用sudo命令了,over
PS:这里用的编辑器是nano,以下是nano简单的保存方式:
linux下在编辑状态下退出请按Ctrl+X,会有两种情形:
①、如果文件未修改,直接退出;
②、如果修改了文件,下面会询问是否需要保存修改。输入Y确认保存,输入N不保存,按Ctrl+C取消返回。如果输入了Y,下一步会提示输入想要保存的文件名。如果不需要修改文件名直接回车就行;若想要保存成别的名字(也就是另存为)则输入新名称然后确定,这个时候也可用Ctrl+C来取消返回。