2017-08-01 58 views
0

嘗試從我的Windows服務訪問本地ActiveDirectory。如何以編程方式將此Active Directory作爲LocalService訪問?

我打算嘗試使用LocalService來訪問它,它在我以管理員身份在Visual Studio中運行它時起作用,但是當我將它作爲實際服務運行時失敗。

我需要以某種方式提供SecurityIdentifierDirectoryEntry嗎?但是,只需要usernamepassword而不是SecurityIdentifier ...

var fqhn = System.Net.Dns.GetHostEntry(Environment.MachineName).HostName; 
using (DirectoryEntry root = new DirectoryEntry(string.Format("LDAP://{0}/RootDSE", fqhn))) 
{ 
    string ctx = root.Properties["configurationNamingContext"].Value.ToString(); 
    string path = string.Format("LDAP://{0}/CN=Microsoft Exchange,CN=Services,{1}", 
           fqhn, ctx); 
    var blah = new DirectoryEntry(path); 
} 

它給我 System.DirectoryServices.DirectoryServicesCOMException (0x80072030): There is no such object on the server.,我試圖在這兩個LocalServiceNetworkService運行的服務。

+0

LocalService和NetworkService都沒有權限連接到您的活動目錄,因爲它們是本地計算機帳戶。你可以嘗試'System',它將使用AD中的計算機賬號,但是你真的應該以AD用戶身份運行你的服務,這樣你就可以只分配需要的權限。 – Ashigore

+0

嗡嗡聲...新的C#在這裏,所以沒有辦法使用系統帳戶來閱讀AD?我真的想避免創建新用戶。在「Active Directory用戶和計算機>用戶」中,如果我通過「委託控制嚮導」添加了「網絡服務」或「本地服務」,是否可行? – codenamezero

+0

不,因爲包括計算機和AD服務器在內的每臺計算機都有自己的網絡和本地服務帳戶。你爲什麼不想創建一個用戶?無論哪種方式,您的計算機上唯一可以訪問AD中的內容的帳戶是系統(計算機)帳戶。 – Ashigore

回答

1

其實,它看起來像我使用錯誤的地址訪問ActiveDirectory。在我的本地機器上,我用的是:

System.Net.Dns.GetHostEntry(Environment.MachineName).HostName; 

但我應該使用代替:

Environment.UserDomainName 

讓我有種發的情況下,回退方法的域不存在。 ..

string domain = Environment.UserDomainName; 
if (String.IsNullOrEmpty(domain)) 
    domain = System.Net.Dns.GetHostEntry(Environment.MachineName).HostName; 

現在連接到LDAP作品:

new DirectoryEntry(string.Format("LDAP://{0}/RootDSE", domain) 

只是爲了證實@Harry Johnston在其他答覆中說過,使用NetworkService工作! (我回到LocalService只是爲了確保它和我失敗)