我有一个使用 pkexec
运行的 python 程序,我想正因为如此,我很难获得 os.environ.get('XDG_CURRENT_DESKTOP')
或 os.environ.get('DESKTOP_SESSION')
输出任何内容。该程序的功能之一是获取 Linux 桌面环境,而这正是我现在要完成的主要工作。我决定使用 os.setupid('my_username')
从 pwd 获取它以切换到我的用户并尝试获取环境变量,因为它不再是 root 但问题是我不能返回并以 root 身份运行脚本以执行其他功能。我怎样才能回到 root 身份呢?
为了获取环境变量,我尝试这样做:
def getDesktopEnvironment(self):
os.seteuid(self.uidChange)
desktops = subprocess.Popen(['bash', 'desktopenv.sh'], stdout=subprocess.PIPE)
desktops.wait()
a = desktops.stdout.read()
print a
if a == "X-Cinnamon":
#do this
elif a == "Unity":
#do that
bash脚本在下面
#!/bin/bash
echo $XDG_CURRENT_DESKTOP
试图回到 root 给我这个:os.seteuid(0)OSError: [Errno 1] Operation not permitted
最佳答案
我建议进行以下更改:
修改为你想要的用户设置UID的代码为你想要的UID对应的用户名。
修改您的 getDesktopEnvironment 使其看起来像下面的代码。 注意:脚本路径不必位于用户主目录中,它只需要由用户名指定的用户可读即可。
def getDesktopEnvironment(self):
# You can set the script_path can be located anywhere you want.
# as long as the user you want to invoke the script has permission
# to read the file.
script_path = os.path.join('~', self.username, 'desktopenv.sh')
args = args = ['sudo', '--login', '-u', self.username, '/bin/bash', script_path]
desktops = subprocess.Popen(args, stdout=subprocess.PIPE)
desktops.wait()
a = desktops.stdout.read()
print a
if a == "X-Cinnamon":
#do this
elif a == "Unity":
#do that
仅仅因为您更改了当前进程的 UID 并不意味着您继承了与该 UID 关联的环境。使用带有 -i
选项的 sudo 可确保运行用户的启动脚本并确保设置所有相关环境变量。
使用 sudo 还可以确保您可以继续以 root 身份运行应用程序的其余部分。
关于python - 如何以不同的用户(本地用户)身份运行通过 root 运行的 python 脚本,然后返回到 root,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42965479/