通过更改sudoer文件来配置sudo 默认home目录以及环境变量

这个问题主要会引起一些软件环境变量方面的困扰,比如使用了 zshsudo -s后发现主题消失,或者其它软件类似的现象,主要原因是使用了sudo -s后当前用户为root用户,环境变量改变,导致配置文件失效。

解决方法:

修改sudoers文件:

sudo visudo
sudo vim/etc/sudoers

添加:

Defaults:用户名 !env_reset

注意:以上修改的仅仅是当前用户的环境变量规则,也就是说,在当前用户下使用sudo不会更改环境变量,但是sudo -s后进入的是root用户,再提权即root用户使用sudo,那么环境变量依然遵循root用户的配置。
如果想root后也保留当前环境配置,需要额外设置,参考下文。

参考:

主要是受到下篇启发

How do I make sudo preserve my environment variables?

Using sudo 1.7.4p4 on Solaris 5.10 and sudo 1.6.7p5 on RHEL4 u6 I can’t see how to preserve my environment variables, for instance $PYTHONPATH. I’ve added this line to sudoers, but it doesn’t make any difference:

Defaults !env_reset

Am I doing something wrong, or is the sudo installation simply not respecting the env_reset flag?

Edit: At least on Solaris, we’ve found that this issue depends on the shell! The standard root shell is Bourne, if we run bash under sudo (sudo bash) on the other hand, !env_preset will preserve the environment (including PATH and LD_LIBRARY_PATH). This is rather confusing behaviour I have to say.

这篇文章展示了对当前用户的变量设置

How do I set environment variable for all users even when doing sudo su?

Is there any way to specify that sudo should preserve certain environment variables for specified commands only? For some purposes I’d like my $HOME env. variable preserved when I run certain commands. For other purposes and other commands, I want it reset. Can this be done with /etc/sudoers?

Edit:

Thank you for the answers. I wonder if I might ask a follow-up question, which is “Why, then, does this not work?”

In the example I’m trying to get working, I want sudo nano to read my $HOME/.nanorc. If I use this:

Defaults:simon env_keep=HOME
it works perfectly. If I use this:

Defaults!/bin/nano env_keep=HOME
or this:

Cmnd_Alias NANO = /usr/bin/nano,/bin/nano,/bin/rnano
Defaults!NANO env_keep=HOME
it’s not working at all. Any suggestions as to why? (I’m on Debian testing, btw.)

(Note: I don’t think it’s nano specific, btw — I can reproduce the behaviour with a one-line bash script that simply echos $HOME).

其他文章

`/etc/sudoers` — specify `env_keep` for one command only?
How is sudo set to not change $HOME in Ubuntu and how to disable this behavior?
    原文作者:Shisui
    原文地址: https://segmentfault.com/a/1190000015256290
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞