Search code examples
pythonwmi

Python --- find current or last logged on user


I am trying to find current or last logged on user

Part of the script

# 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

I get the following output

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

Do these numbers represent recently and currently logged on users? How to convert them to DOMAIN\username format? And if they can be converted, how to get latest user?

EDIT

I tried

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

But I get error

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)>

Then I tried

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

But I get the error

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

How do I troubleshoot these?


Solution

  • You have to dig down a bit to get the added info. Unfortunately, I can't recall my source for this:

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

    You can get the properties printed from that as well, for example replace the final line with:

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

    I get:

    MyPC\nerdwaller
    

    edit

    I should have mentioned two things:

    1. I am using Python3, so for you to use print as a function in python 2.x:

      from __future__ import print_function

    2. There are issues iterating through that, as you are seeing. There are various solutions, and since I don't know your use-case... not the cleanest solution, you can wrap that in a try/catch:

     

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