跳到主要内容

2、实战:linux机器普通用户配置sudo免密功能-2024.4.29(测试成功)

实战:linux机器普通用户配置sudo免密功能-2024.4.29(测试成功)

问题背景

另一个问题是,很多时候,我们本来就登录了,每次使用sudo还要输入密码就显得烦琐了。我们可不可以不再输入密码呢?当然可以,我们这样修改配置文件:

解决方法

visudo
……
root ALL=(ALL) ALL
test ALL=(ALL) NOPASSWD:ALL

==注意wheel组问题:==

注意:看用户是否加入到了wheel组里?

因为在/etc/sudoers里有如下默认配置:

image-20240429111634662

Allows people in group wheel to run all commands

%wheel ALL=(ALL) ALL

只要是这个组的用户,就可以执行all的linux命令,但是如果要设置免密,就要将这行内容给注释掉,然后把下面内容给放开。

Same thing without a password

%wheel ALL=(ALL) NOPASSWD: ALL

这样才能实现用户sudo免密。

那么什么用户会是wheel组下的用户呢?

一般是机器做了禁止任何人su到root加固项,

1、编辑su文件(vi /etc/pam.d/su),添加下面行: auth sufficient pam_rootok.so auth required pam_wheel.so use_uid

2、补充操作说明: 上述添加表明只有wheel组的成员可以使用su命令成为root用户。可以把有需求的用户添加到wheel组,以使它可以使用su命令成为root用户。 添加方法: #usermod -G wheel username

现在还有个问题:某个用户指定了一个扩展组(usermod -G wheel ZXL),但是如何删除这个扩展组呢?用什么命令来着?-->用gpasswd -d ZXL wheel就好了。

所以,具体设置用户sudo免密的方式如下:

情况1:用户已经加到wheel组里了。

visudo
……
test2 ALL=(ALL) ALL

## Allows people in group wheel to run all commands
#%wheel ALL=(ALL) ALL ##注释这行内容

## Same thing without a password ##只要是加到这个wheel组里的用户,都可以执行all linux命令的; ##取消注释这样内容
%wheel ALL=(ALL) NOPASSWD: ALL

情况2:用户未加到wheel组里。

visudo
……
test ALL=(ALL) NOPASSWD:ALL ##直接配置这样内容就好。
  • 验证(符合预期)
[root@test1 ~]#su - test
Last login: Mon Apr 29 11:18:22 CST 2024 on pts/0
[test@test1 ~]$sudo ls /root
hellodb_innodb.sql mysql-5.6.47-linux-glibc2.12-x86_64.tar.gz profile

其它

==案例:也可以对单个命令进行配置sudo免密功能(比较少用)==

  • 使用方法:
[root@test ~]# visudo
HG ALL= /bin/mount,/bin/umount,sudoedit,NOPASSWD:/bin/cat /var/log/messages #注意,哪个命令需要免密就在前面加上NOPASSWD:即可,其他没加这个参数的命令再次使用依然需要输入自己的密码的
  • 测试过程:
测试过程:
[wang@test ~]$ ll /var/log/messages
-rw------- 1 root root 90047 Feb 13 17:57 /var/log/messages
[wang@test ~]$ cat !$
cat /var/log/messages
cat: /var/log/messages: Permission denied
[wang@test ~]$ sudo cat /var/log/messages
Sorry, user wang is not allowed to execute '/bin/cat /var/log/messages' as root on test.


[wang@test ~]$ sudoedit /etc/sudoers
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
wang ALL= /bin/mount,/bin/umount,sudoedit,NOPASSWD:/bin/cat /var/log/messages #添加NOPASSWD参数

[wang@test ~]$ sudo cat /var/log/messages
[wang@test ~]$
Feb 13 17:59:56 test prometheus: level=warn ts=2021-02-13T09:59:56.561Z caller=scrape.go:1094 component="scrape manager" scrape_pool=prometheus target=http://localhost:9090/metrics msg="Appending scrape report failed" err="out of bounds"
Feb 13 17:59:58 test prometheus: level=warn ts=2021-02-13T09:59:58.995Z caller=scrape.go:1094 component="scrape manager" scrape_pool=node2 target=http://192.168.10.12:9100/metrics msg="Appending scrape report failed" err="out of bounds"