设置sudo不输入密码 sudoers 编辑出错后的补救方法

一 设置sudo为不需要密码

有时候我们只需要执行一条root权限的命令也要su到root,是不是有些不方便?这时可以用sudo代替。默认新建的用户不在sudo组,需要编辑/etc/sudoers文件将用户加入,该文件只能使用visudo命令,

1) 首先需要切换到root, su - (注意有- ,这和su是不同的,在用命令"su"的时候只是切换到root,但没有把root的环境变量传过去,还是当前用乎的环境变量,用"su -"命令将环境变量也一起带过去,就象和root登录一样)

2) 然后 visudo 或者 vi /etc/sudoers, visudo 这个和vi的用法一样,由于可能会有人不太熟悉vi,所以简要说一下步骤

移动光标,到一行root ALL=(ALL)   ALL的下一行,按a,进入append模式,输入
your_user_name ALL=(ALL)   ALL

然后按Esc,再输入:w保存文件,再:q退出

这样就把自己加入了sudo组,可以使用sudo命令了。

3) 默认5分钟后刚才输入的sodo密码过期,下次sudo需要重新输入密码,如果觉得在sudo的时候输入密码麻烦,把刚才的输入换成如下内容即可:
your_user_name ALL=(ALL) NOPASSWD: ALL

至于安全问题,对于一般个人用户,我觉得这样也可以的。

4)如果你想设置只有某些命令可以sudo的话,your_user_name   ALL= (root) NOPASSWD: /sbin/mount, (root) NOPASSWD: /bin/umount, (root) NOPASSWD: /mnt/mount, (root) NOPASSWD: /bin/rm, (root) NOPASSWD: /usr/bin/make, (root) NOPASSWD: /bin/ln, (root) NOPASSWD: /bin/sh, (root) NOPASSWD: /bin/mv, (root) NOPASSWD: /bin/chown, (root) NOPASSWD: /bin/chgrp, (root) NOPASSWD: /bin/cp, (root) NOPASSWD: /bin/chmod

 

注意: 有的时候你的将用户设了nopasswd,但是不起作用,原因是被后面的group的设置覆盖了,需要把group的设置也改为nopasswd。

joe ALL=(ALL) NOPASSWD: ALL

%admin ALL=(ALL) NOPASSWD: ALL

 

参考: 

http://blog.163.com/love-love-l/blog/static/21078304201071232234518/

 

 

二 设置su为不需要密码
如果需要对某用户su命令也不需要输入密码,则需要修改下列的:

1)切换到root权限;
2)创建group为wheel,命令为groupadd wheel;
3)将用户加入wheel group中,命令为usermod -G wheel joe;
4)修改su的配置文件/etc/pam.d/su,增加下列项:
 auth       required   pam_wheel.so group=wheel
# Uncomment this if you want wheel members to be able to
# su without a password.
 auth       sufficient pam_wheel.so trust use_uid

至此你可以使用例如如下的命令且不需要输入密码:su joe -c command。

 

参考:

 

http://cosminswiki.com/index.php/How_to_let_users_su_without_password
http://ag-up.com/?p=457
 
二 sudoers 编辑出错后的补救方法
/etc/sudoers: syntax error near line 
sudo: parse error in /etc/sudoers near line 25 
sudo: no valid sudoers sources found, quitting 
终极解决方案: 

1. shift进入recovery模式 
2. 选中root账号 
3. chmod 666 /dev/null 
   mount -o remount rw / 
4. nano /etc/sudoers 
恢复本文件内容并存盘。 

# /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
原文地址:https://www.cnblogs.com/xiaotlili/p/3210617.html