Python --- 查找当前或上次登录的用户

标签 python wmi

我正在尝试查找当前或上次登录的用户

部分脚本

# userIP has been defined
# try to access wmi

try:
    c = wmi.WMI(userIP)
except: 
    print "Cannot access WMI for", userIP
    sys.exit()


for os in c.Win32_OperatingSystem():
    print os.Caption

for us in c.Win32_LogonSession():
    print us.LogonId

我得到以下输出

Microsoft Windows 7 Enterprise
999
997
996
4831418
8883496
8883473
8883457
8883437
671914

这些数字是否代表最近和当前登录的用户?如何将它们转换为 DOMAIN\username 格式?如果可以转换,如何获取最新用户?

编辑

我试过了

for us in c.Win32_LogonSession():
    for user in us.references("Win32_LoggedOnUser"):
        print(user.Antecedent)

但是我得到错误

Traceback (most recent call last):
  File ".\lookup.py", line 48, in <module>
    print(user.Antecedent)
  File "D:\Python27\lib\site-packages\wmi.py", line 555, in __getattr__
    return WMI (moniker=value)
  File "D:\Python27\lib\site-packages\wmi.py", line 1290, in connect
    handle_com_error ()
  File "D:\Python27\lib\site-packages\wmi.py", line 241, in handle_com_error
    raise klass (com_error=err)
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217406, 'OLE error 0x80041002', No
ne, None)>

然后我试了一下

for us in c.Win32_LogonSession():
    for user in us.references("Win32_LoggedOnUser"):
        print(user.Antecedent.Domain, user.Antecedent.Name, sep="\\")

但是我得到了错误

  File ".\lookup.py", line 48
    print(user.Antecedent.Domain, user.Antecedent.Name, sep="\\")
                                                           ^
SyntaxError: invalid syntax

如何解决这些问题?

最佳答案

您必须深入挖掘才能获得附加信息。不幸的是,我不记得我的来源:

for us in c.Win32_LogonSession():
    for user in us.references("Win32_LoggedOnUser"):
        print(user.Antecedent)

您也可以从中打印属性,例如将最后一行替换为:

print(user.Antecedent.Domain, user.Antecedent.Name, sep="\\")

我得到:

MyPC\nerdwaller

编辑

我应该提到两件事:

  1. 我正在使用 Python3,因此您可以在 python 2.x 中将 print 用作函数:

    from __future__ import print_function

  2. 如您所见,问题反复出现。有多种解决方案,由于我不知道您的用例...不是最干净的解决方案,您可以将其包装在 try/catch 中:

for us in c.Win32_LogonSession():
    try:
        for user in us.references("Win32_LoggedOnUser"):
            print(user.Antecedent)
    except:
        pass

关于Python --- 查找当前或上次登录的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23498307/

相关文章:

windows - 如何将软件注册为 Windows 7 防病毒软件?

windows - 我如何知道 Windows 是否刚刚从 BSOD 恢复?

powershell - 将 WMI 创建日期转换为格式表

python /OpenCV : Computing a depth map from stereo images

python - matplotlib:在条形图上绘制多列 Pandas 数据框

c++ - WMI 给我不完整的硬件信息 (PhysicalMemory)

c# - 在 64 位操作系统上的进程内 wmi 提供程序(32 位)中加载 native dll(32 位)

Python:索引列表列表的问题

python - 如何使用多个 contains 变量简化 .str.contains 代码?

python - 如何判断某些源代码中导入了哪些模块?