leafee98-blog/content/essays/preserve-some-env-variable-when-sudo.md

39 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "在 sudo 中保留部分环境变量"
date: 2022-02-14T23:23:35+08:00
tags: []
categories: []
weight: 50
show_comments: true
draft: false
---
默认情况下,通过 sudo 在运行程序时,会重置一个运行环境,以“最小化”的环境的形式运行目标程序,该环境中仅存在几个预先定义的变量,此外可以通过 `env_keep``env_check` 两个选项来从当前运行环境中继承已有的环境变量。
## 从当前运行环境保留环境变量
`sudo` 具有 `-preserve-env` 参数,可以从当前环境中保留参数
## 仅保留从特定文件中定义的环境变量
这里使用的发行版为 Debian bullseyePAM 服务文件因发行版不同,其文件内容亦大不相同,本文仅供参考,自行修改 PAM 文件需谨慎。
*On systems that support PAM where the pam_env module is enabled for sudo, variables in the PAM environment may be merged in to the environment. If a variable in the PAM environment is already present in the user's environment, the value will only be overridden if the variable was not preserved by sudoers.*
在为 sudo 启用 `pam_env` 模块的系统中,则从 PAM 中读入和变量会合并到环境变量中,若干 PAM 中所导入的某一个变量在当前用户环境中已经存在,那么该变量会保持当前用户环境中的值,除非在 sudoer 的配置中该变量未被保留。
`/etc/pam.d/sudo` 中添加如下配置,可从 `/etc/security/pam_env.conf` 文件中获取环境变量。这行配置项的来源是 `/etc/pam.d/su`,因 `su` 命令执行后会从 `pam_env.conf` 中导入环境变量而 `sudo` 不会,并且两个命令分别使用的 PAM 服务名称为 `su``sudo`,遂参考并修改。
```
# This module parses environment configuration file(s)
# and also allows you to use an extended config
# file /etc/security/pam_env.conf.
#
# parsing /etc/environment needs "readenv=1"
session required pam_env.so readenv=1
```
参考:
[https://www.sudo.ws/docs/man/1.8.15/sudoers.man/#Command_environment](https://www.sudo.ws/docs/man/1.8.15/sudoers.man/#Command_environment)