如何在su-中保留环境变量?

服务器故障

当使用ssh到远程系统时,我导出LC_ALL="en_US.UTF-8"(通过sendEnvssh_config中)。当我su - user123通过登录shell重置此变量时。LC_xxx当以远程系统上的另一个用户身份执行登录shell时,是否可以保留此变量(以及其他变量)?

我意识到我可以在执行完外壳程序或~/.bashrc目标用户的输入后手动导出变量,但是ssh如果可能,我宁愿保留原始值谢谢。

编辑:我确实需要初始化用户环境的特定部分,这就是为什么su -要使用它。我只想保留LC_xxx

服务器故障

我发现su有一个保存环境的选项:

-m, -p, --preserve-environment
           Preserve the current environment, except for:
...

这样,将执行目标用户的shell初始化文件,就像执行登录shell一样,但是如果任何LC_xxx变量已经包含有效值,则可以对其进行测试并且不对其进行初始化。

编辑:只是注意,我能够通过添加一个脚本/etc/profile.d/ssh_lc_vars.sh处理导出的LC_xxx变量从而在整个系统中应用。我还必须对未处理的未初始化环境变量做一些额外的工作su -ml userxxx以下是更多示例,因为我无法包含整个脚本。如果有人可以改进它,那就更好了。

...
# clean up client-side variable for junk
lc_sanitize()
{
   arg="$1"
   # first, strip underscores
   clean="${arg//_/}"

   # next, replace spaces with underscores
   clean="${clean// /_}"

   # now, clean out anything that's not alphanumeric, underscore, hypen or dot
   ret="${clean//[^a-zA-Z0-9_\.-]/}"

   # return santized value to caller
   echo "$ret"
}

# LC_MY_LANG comes from an ssh client environment. If empty,
# this isn't a remote ssh user, but set it locally so this user
# can connect elsewhere where this script runs
if [ -z "$LC_MY_LANG" ]; then
   # force an LC_xxx setting for the environment
    LC_MY_LANG="en-US.utf-8"
else
    # otherwise, use the LC_xxxx variable from the ssh environment
    # 2017-01-30 - when using "su --preserve-environment  userxxx --login" be sure to fixup needed variables
    # shorthand: su -ml user111
    export USER=`whoami`
    export LOGNAME=${USER}
    export HOME=$( getent passwd "$USER" | cut -d: -f6 )
    cd ${HOME}

    # sanitize variable which was set client-side and log it
    u_sanitized=$(lc_sanitize "$LC_MY_LANG")
    echo "Notice: LC_MY_LANG sanitized to $u_sanitized from $SSH_CLIENT as user $USER" | logger -p auth.info
fi

# mark variable read-only so user cannot change it then export it
readonly LC_MY_LANG
# set terminal to LC_MY_LANG
export LC_LANG=${LC_MY_LANG}
export LC_MY_LANG
...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章