通过更改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?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值