我正在尝试查找当前或上次登录的用户
部分脚本
# 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
编辑
我应该提到两件事:
我正在使用 Python3,因此您可以在 python 2.x 中将 print 用作函数:
from __future__ import print_function
如您所见,问题反复出现。有多种解决方案,由于我不知道您的用例...不是最干净的解决方案,您可以将其包装在 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/