简体   繁体   English

如何从使用 pkexec 运行的脚本中获取当前用户名?

[英]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.

相关问题 如何获取 Atom 的脚本 package 以从脚本的当前工作目录运行脚本? - How can I get Atom's script package to run a script from the script's current working directory? 如何使用 pkexec 执行 Python 脚本 - How to Execute Python Script Using pkexec 我可以在当前shell中从python脚本运行shell命令吗 - Can I run a shell command from python script in the current shell 如何从 django 用户模型中获取用户名 - How can I get a username from django User Model 尝试从脚本执行二进制文件时,pkexec“找不到这样的文件或目录” - pkexec "no such file or directory found" when trying to execute a binary from a script 当我运行包含bash脚本中的颜色的命令时,如何获取原始字符串 - How can I get raw string when I run a command that includes color from bash script 如何从外部python脚本正确运行scrapy蜘蛛并获取其项目输出 - How can I properly run scrapy spiders from an external python script and get its item output 如何让我的 Python 脚本从我的 dotnet 核心 windows 服务运行? - How can I get my Python script to run from my dotnet core windows service? 如何在Django 1.10中获取当前的“用户名”? - How do I get the current “username” in django 1.10? 如何获取用户的用户名? - How can I get the user's username?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM