[英]How can I get the current username from a script run with pkexec?
I'm executing a python script as root with pkexec
and I'm using working_dir = os.getenv('HOME')
to get the username but it always returns root instead of test1 which is the current user.我正在使用 pkexec 以 root 身份执行
pkexec
脚本,我正在使用working_dir = os.getenv('HOME')
来获取用户名,但它总是返回 root 而不是当前用户 test1。
How can I get the user that ran pkexec
instead?我怎样才能得到运行
pkexec
的用户呢?
Script is located in /usr/bin if that information is any use.如果该信息有任何用处,脚本位于 /usr/bin 中。
The sudo
man page describes the environment variables which hold the information of the user who invoked it. sudo
手册页描述了环境变量,这些环境变量保存了调用它的用户的信息。
import os
print os.environ["SUDO_USER"]
Thanks to that other guy, in the end, below is what I did to get the current user: 最后,感谢另一个人,下面是我为获取当前用户所做的事情:
import os
import pwd
user = pwd.getpwuid(int(os.environ["PKEXEC_UID"])).pw_name
working_dir = '/home/' + user
For those looking for a pure bash solution, this finds the user run with sudo or pkexec:对于那些寻找纯 bash 解决方案的人,这会发现用户使用 sudo 或 pkexec 运行:
if test -z "$SUDO_USER"
then
USER=$(getent passwd $PKEXEC_UID | cut -d: -f1)
else
USER=$SUDO_USER
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.