Loading

批量修改ubuntu用户sudo免密码

TL;DR

假设用户名为user密码是hello

echo hello | sudo -S sh -c "echo 'user ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers.d/user-nopasswd"
sudo chmod 440 /etc/sudoers.d/user-nopasswd

设想

每次输入sudo密码很繁琐,希望sudo免密码执行
对应很多服务器,写shell脚本批量修改

思考

网上多数方法通过向/etc/sudoers文件末尾插入user ALL=NOPASSWD:ALL实现免密
文件头部如下

#
# 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.
#

官方建议我们不要直接修改本文件而是使用sudoer.d中的本地设置

#
# As of Debian version 1.7.2p1-1, the default /etc/sudoers file created on
# installation of the package now includes the directive:
# 
# 	#includedir /etc/sudoers.d
# 
# This will cause sudo to read and parse any files in the /etc/sudoers.d 
# directory that do not end in '~' or contain a '.' character.
# 
# Note that there must be at least one file in the sudoers.d directory (this
# one will do), and all files in this directory should be mode 0440.
# 
# Note also, that because sudoers contents can vary widely, no attempt is 
# made to add this directive to existing sudoers files on upgrade.  Feel free
# to add the above directive to the end of your /etc/sudoers file to enable 
# this functionality for existing installations if you wish!
#
# Finally, please note that using the visudo command is the recommended way
# to update sudoers content, since it protects against many failure modes.
# See the man page for visudo for more information.
#

系统会自动加载sudoers.d文件夹下名称不含~.的文件

实现

假设用户名为user密码是hello

推荐方法:添加本地sudoers.d

echo hello | sudo -S sh -c "echo 'user ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers.d/user-nopasswd"
sudo chmod 440 /etc/sudoers.d/user-nopasswd

不推荐方法:直接修改sudoers

echo hello | sudo -S sed -i '$a user ALL=(ALL) NOPASSWD: ALL' /etc/sudoers
posted @ 2020-09-15 10:34  azureology  阅读(491)  评论(0编辑  收藏  举报