title: Python --- find current or last logged on user
body: <p>I am trying to find current or last logged on user</p>
  
  <p>Part of the script </p>
  
  <pre><code># 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
  </code></pre>
  
  <p>I get the following output</p>
  
  <pre><code>Microsoft Windows 7 Enterprise
  999
  997
  996
  4831418
  8883496
  8883473
  8883457
  8883437
  671914
  </code></pre>
  
  <p>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?</p>
  
  <p>EDIT</p>
  
  <p>I tried </p>
  
  <pre><code>for us in c.Win32_LogonSession():
      for user in us.references("Win32_LoggedOnUser"):
          print(user.Antecedent)
  </code></pre>
  
  <p>But I get error</p>
  
  <pre><code>Traceback (most recent call last):
    File ".\lookup.py", line 48, in &lt;module&gt;
      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: &lt;x_wmi: Unexpected COM Error (-2147217406, 'OLE error 0x80041002', No
  ne, None)&gt;
  </code></pre>
  
  <p>Then I tried </p>
  
  <pre><code>for us in c.Win32_LogonSession():
      for user in us.references("Win32_LoggedOnUser"):
          print(user.Antecedent.Domain, user.Antecedent.Name, sep="\\")
  </code></pre>
  
  <p>But I get the error</p>
  
  <pre><code>  File ".\lookup.py", line 48
      print(user.Antecedent.Domain, user.Antecedent.Name, sep="\\")
                                                             ^
  SyntaxError: invalid syntax
  </code></pre>
  
  <p>How do I troubleshoot these?</p>