Я обнаружил, что в su
есть опция сохранения среды:
-m, -p, --preserve-environment
Preserve the current environment, except for:
...
Таким образом, инициализирующие файлы оболочки целевого пользователя выполняются, как и при входе в систему, но любые переменные LC_xxx
могут быть проверены и не инициализированы, если они уже содержат правильное значение.
EDIT: Просто примечание, я смог применить это в масштабах всей системы, добавив скрипт в /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
...