简体   繁体   中英

Check if user is a local admin on external machine

I'm writing an app that aggregates all the event log entries on each of several different servers. I can get the event logs by passing in the MachineName to EventLog.GetEventLogs . This will typically fail at some stage is the user is not a local administrator on that machine, so I'd like to check for it ahead of time and skip to the next set of servers if that is the case

For Each svr As String In Servers

    'TODO: check to see if they are a local administrator, else continue for

    Dim logs As List(Of EventLog) = EventLog.GetEventLogs(svr).ToList
    For Each log As EventLog In logs
        LoadEachOSLogEntry(log)
    Next
Next

Most solutions, like the one here , only check if the user is an admin on the currently executing machine.

Dim user As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim principal As New WindowsPrincipal(user)
Dim isAdmin As Boolean = principal.IsInRole(WindowsBuiltInRole.Administrator)

Here's an attempt.

The following function will return whether or not a user belongs to a particular user group (in my case "Administrators" ) on any machine.

Imports System.DirectoryServices.AccountManagement

Public Shared Function IsMemberOfGroup(userName As String, machineName As String, memberGroup as String) As Boolean
    Dim isMember As Boolean = False
    Using rootContext As New PrincipalContext(ContextType.Machine, machineName), _
          grp As GroupPrincipal = GroupPrincipal.FindByIdentity(rootContext, memberGroup), _
          usr As UserPrincipal = UserPrincipal.FindByIdentity(rootContext, IdentityType.SamAccountName, userName)
        If grp IsNot Nothing AndAlso usr IsNot Nothing Then
            ' Check if the user is a member of the group.
            isMember = grp.GetMembers(True).Contains(usr)
        Else
            isMember = False
        End If
    End Using
    Return isMember
End Function

The caveat is that the user running the method has to be an admin in order to have rights to this information set in PrincipalContext . I was hoping that the application would be able to determine if the user running the application is an admin.

The only way to make this super helpful is to call it and see if it came up with "Access Denied", similar to hometoast already suggested, but this still doesn't feel super "clean"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM