我正在尝试查找当前或上次登录的用户
脚本的一部分
# 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
如何解决这些问题?
答案 0 :(得分:4)
你必须深入挖掘才能获得更多信息。不幸的是,我不记得我的来源:
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
答案 1 :(得分:3)
接受的答案会返回许多用户,包括您自己以及可能登录的用户。
我发现发现登录用户的更可靠方法是获取explorer.exe
进程的所有者。
尝试以下操作获取包含远程Windows计算机当前登录用户的域和用户名的精美元组:
import wmi
c = wmi.WMI('target_hostname')
for process in c.Win32_Process(name='explorer.exe'):
print process.GetOwner()
如果没有人登录并且您想要最后一个人,您可以尝试以下操作获取远程Windows计算机最近登录用户的SID:
import wmi
c = wmi.WMI('target_hostname')
profiles = []
for up in c.Win32_UserProfile():
profiles.append((up.LastUseTime, up.SID, up.LocalPath))
profiles.sort(reverse=True)
for p in profiles:
print p
profiles
列表的第一个元素将包含最近登录的用户。不幸的是,这只是SID。 LocalPath
部分至少可以告诉您他们的用户名,如果您查看他们的主目录名称(并不总是可靠的)。我不确定如何将SID转换为Python中的用户名。