2013-02-26 49 views
1

我正在編寫一個應用程序,它聚合了幾個不同服務器上的所有事件日誌條目。我可以通過傳遞MachineNameEventLog.GetEventLogs來獲取事件日誌。這通常會在某個階段失敗,因爲用戶不是該機器上的本地管理員,所以我想提前檢查並跳到下一組服務器(如果情況如此)檢查用戶是否是外部計算機上的本地管理員

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 

大多數解決方案(如here)只會檢查用戶是否是當前正在執行的計算機上的管理員。

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

旁白:處理偶爾的失敗不是更容易嗎?而不是對目標機器執行一些WMI調用並解析該用戶的權限。 這只是我作爲「我怎麼能告訴我是否可以寫入文件?」的同一類型的問題罷了。答案是「做到這一點,並處理錯誤」 – hometoast 2013-02-26 18:44:33

+0

我認爲在發生錯誤之前最好先處理容易避免的錯誤。如果我可以提前檢查priveleges,我寧願不承擔處理一長串服務器中幾乎所有服務器的異常的成本。另外,我現在擁有結構化的方式,可以將權限信息臨時保存在服務器列表中,因此不需要進行兩次調用即可檢查。在catch塊中很難做到這一點,除了權限之外的任何數量的問題都可能在手邊。 – KyleMit 2013-02-26 19:01:00

+0

@Kyle:異常的成本比單個網絡呼叫便宜幾個數量級。 – 2013-02-27 18:40:05

回答

0

我將分享部分解決,但我不與它完全滿意,所以如果任何人有什麼好,我會高興地接受他們的答案。

在任何機器上,以下函數將返回是否屬於特定用戶組的用戶(在本例中爲"Administrators")。

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 

的caviat是運行方法的用戶必須以有權此信息PrincipalContext設置管理員。我希望應用程序能夠確定運行該應用程序的用戶是否是管理員。

,使這個超級有幫助的唯一方法是調用它,看看它是否想出了「拒絕訪問」,類似於hometoast已經建議,但是這仍然沒有手感超「乾淨」

相關問題