We help IT Professionals succeed at work.

.net 2.0 find what userid is logged into an XP machine

chadmanvb
chadmanvb asked
on
I will have a service that will run on an XP machine and run as system.  I need to write a script that this service will call and report back the current user logged in, their display name, and if they logged in via the console or a remote desktop session.  I know a little visual basic .net but was sure how to tell how the user logged in, such as console or remote desktop.  I was also not sure how to find the current user.  I know System.Environment.UserName works, but I think that shows the user running the app, not the current logged on user.  Any help would be great.
Comment
Watch Question

Kalpesh ChhatralaSoftware Consultant
CERTIFIED EXPERT

Commented:

Author

Commented:
That does the same think as System.Environment.UserName.  It will only show the user that runs the application and not the current user.  I also need to be able to see how they logged into the machine, console or remote desktop.
Paul MacDonaldDirector, Information Systems
CERTIFIED EXPERT

Commented:
Try the System.Security.Principal.WindowsIdentity namespace.  I think System.Security.Principal.WindowsIdentity.Name is what you're after.
Paul MacDonaldDirector, Information Systems
CERTIFIED EXPERT

Commented:
Um, that may only be available .Net 4 so if I led you astray, I apologize.

There's more information here:
http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=VS.80).aspx

Author

Commented:
Well I can compile this in 2.0, but it's not giving me the current logged in user.  When I use runas and run it as another user it gives me that user instead.

Imports System.Security.Principal

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 
        Dim action_username As String = System.Security.Principal.WindowsIdentity.GetCurrent().Name
        MsgBox(action_username)

    End Sub
End Class
Paul MacDonaldDirector, Information Systems
CERTIFIED EXPERT

Commented:

Author

Commented:
I still cant get it to work.  I keep geting the user that runs that appicaion.  I saw that one example, but it used WMI and I was trying to abvoid that.

Imports System.Security
Imports System.Security.Principal
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim loggedOnUserIdentity As WindowsIdentity = WindowsIdentity.GetCurrent()
        MsgBox(loggedOnUserIdentity.Name)
       End Sub
End Class

Author

Commented:
Well I just setup a service to run under the system account and it's still not showing me the local user.  Here is the code:
Imports System.Security
Imports System.Security.Principal
Imports System.IO

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

 


        'Get the current identity and put it into an identity object.
        Dim MyIdentity As WindowsIdentity =
        WindowsIdentity.GetCurrent()

        'Put the previous identity into a principal object.
        Dim MyPrincipal As New WindowsPrincipal(MyIdentity)

        'Principal values.
        Dim PrincipalName As String = MyPrincipal.Identity.Name
        Dim PrincipalType As String =MyPrincipal.Identity.AuthenticationType
        Dim PrincipalAuth As String =MyPrincipal.Identity.IsAuthenticated.ToString()



        'Identity values.
        Dim IdentName As String = MyIdentity.Name
        Dim IdentType As String = MyIdentity.AuthenticationType
        Dim IdentIsAuth As String =MyIdentity.IsAuthenticated.ToString()
        Dim ISAnon As String = MyIdentity.IsAnonymous.ToString()
        Dim IsG As String = MyIdentity.IsGuest.ToString()
        Dim IsSys As String = MyIdentity.IsSystem.ToString()
        Dim Token As String = MyIdentity.Token.ToString()

       
        TextBox1.Text = "IdentName= " & IdentName & vbCrLf _
 & "IdentType= " & IdentType & vbCrLf _
  & "IdentIsAuth= " & IdentIsAuth & vbCrLf _
   & "ISAnon= " & ISAnon & vbCrLf _
    & "IsG= " & IsG & vbCrLf _
     & "IsSys= " & IsSys & vbCrLf _
      & "Token= " & Token & vbCrLf & vbCrLf & vbCrLf _
      & "PrincipalName= " & PrincipalName & vbCrLf _
      & "PrincipalType= " & Token & vbCrLf _
       & "PrincipalAuth= " & Token & vbCrLf

        Dim strlist As String

        strlist = "IdentName= " & IdentName & vbCrLf _
 & "IdentType= " & IdentType & vbCrLf _
  & "IdentIsAuth= " & IdentIsAuth & vbCrLf _
   & "ISAnon= " & ISAnon & vbCrLf _
    & "IsG= " & IsG & vbCrLf _
     & "IsSys= " & IsSys & vbCrLf _
      & "Token= " & Token & vbCrLf & vbCrLf & vbCrLf _
      & "PrincipalName= " & PrincipalName & vbCrLf _
      & "PrincipalType= " & Token & vbCrLf _
       & "PrincipalAuth= " & Token & vbCrLf

        IO.File.WriteAllText("c:\temp\chadtest.txt", strlist)


    End Sub
End Class


IdentName= NT AUTHORITY\SYSTEM
IdentType= Negotiate
IdentIsAuth= True
ISAnon= False
IsG= False
IsSys= True
Token= 360


PrincipalName= NT AUTHORITY\SYSTEM
PrincipalType= 360
PrincipalAuth= 360
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
>Well I just setup a service to run under the system account and it's still not showing me the local user.

Its because System is the local user for the service. Service will run if there is no one logged into the system.

Author

Commented:
CodeCruiser, Well the other problem I have is it does not give me the logged in user.  If I run it as myself I will see my id, or if I run it with my admin account I will see that.  I'm just trying to find the user that accually logged into the machine, not what my application is running as.
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014
Commented:
Try the following

http://altfo.wordpress.com/2010/11/25/get-logged-in-user-while-impersonate-or-run-as-admin/


Code below converted to VB
Public Shared Function GetParentUser(pid As Integer) As String
	Dim parentUserAccount As String = Nothing
	Dim queryString As String = [String].Format("select ParentProcessId from win32_process where ProcessId={0}", pid)
	Using query As New ManagementObjectSearcher(New SelectQuery(queryString))
		For Each mo As ManagementObject In query.[Get]()
			Dim parentPid As UInteger = CUInt(mo.Properties("ParentProcessId").Value)
			queryString = [String].Format("select Handle from win32_process where ParentProcessId = {0}", parentPid)
			Using subQuery As New ManagementObjectSearcher(New SelectQuery(queryString))
				For Each mo1 As ManagementObject In subQuery.[Get]()
					Dim handle As String = DirectCast(mo1.Properties("Handle").Value, String)
					Dim relatedQuery As New RelatedObjectQuery("associators of {Win32_Process.Handle=""" & handle & """}")
					relatedQuery.RelatedClass = "Win32_LogonSession"
					Using relQuery As New ManagementObjectSearcher(relatedQuery)
						For Each mo2 As ManagementObject In relQuery.[Get]()
							Dim relQuery2 As New RelatedObjectQuery("associators of {Win32_LogonSession.LogonId='" + mo2("LogonId") & "'}")
							relQuery2.RelationshipClass = "win32_LoggedonUser"
							Using searcher2 As New ManagementObjectSearcher(relQuery2)
								For Each mo3 As ManagementObject In searcher2.[Get]()
									parentUserAccount = [String].Format("{0}\{1}", mo3("Domain"), mo3("Name"))
								Next
							End Using
						Next
					End Using
				Next
			End Using
		Next
	End Using
	Return parentUserAccount
End Function

Open in new window