简体   繁体   English

python-获取会话用户

[英]python - get the session user

I'm running the same Python script for different users on my PC (Windows 10). 我在PC(Windows 10)上为不同用户运行相同的Python脚本。 This script has to get the user who is actually logged in. For example getpass.getuser() isn't working because it just returns the user for which the Python script is running. 该脚本必须获取实际登录的用户。例如, getpass.getuser()不起作用,因为它仅返回正在为其运行Python脚本的用户。 How can I get this? 我怎么能得到这个? Thanks for help! 感谢帮助!

The whole point of Run as... is to mimic the environment of another user so, naturally, when you query for the username (which essentially gets you the value of %USERNAME% env. variable) you'll get the one under which you're running the script. 运行为...”的重点是模仿另一个用户的环境,因此,自然而然地,当您查询用户名时(本质上会获得%USERNAME% env。变量的值),您将得到一个您正在运行脚本。

To get the currently logged in user, you'll have prod the current session, and to do that, at the very least, you'll have to query WMIC (or access the Win32 API directly). 要获取当前登录的用户,您需要提供当前会话,并且至少必须查询WMIC(或直接访问Win32 API)。 Something like: 就像是:

import subprocess

def get_session_user():
    res = subprocess.check_output(["WMIC", "ComputerSystem", "GET", "UserName"],
                                  universal_newlines=True)
    _, username = res.strip().rsplit("\n", 1)
    return username.rsplit("\\", 1)

Beware that this will return a tuple containing both the system/domain of the currently logged-in user and the username itself, so call it as: 请注意,这将返回一个包含当前登录用户的系统/域和用户名本身的元组,因此将其称为:

system, username = get_session_user()

To get both. 两者兼得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM