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

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

解决方法:

修改sudoers文件:

sudo visudo
sudo vim/etc/sudoers

添加:

Defaults:用户名 !env_reset

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

参考:

主要是受到下篇启发

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:vim

Defaults !env_reset

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

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

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

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:unix

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

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

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

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

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?
相关文章
相关标签/搜索