[英]How to control windows services from remote computer in local network?
我首先道歉,因為它似乎是重復的問題。 但是即使我遇到了兩個非常相似的Google,我也做了很多事情:
但不幸的是,他們都沒有為我工作。
我已經開發了在Windows Server 2008 R2標准計算機上運行的Windows服務。
服務運行得很好,並且可以正常工作。
我的問題是我想制作一個可以在我們的本地網絡上運行的桌面應用程序。 從這個應用程序中,我想執行一些基本操作,例如獲取服務狀態,停止和重新啟動。
這是我的工作。
private void WSControllerForm_Load(object sender, System.EventArgs e)
{
ConnectionOptions options = new ConnectionOptions();
options.Password = "password";
options.Username = "Administrator";
options.Impersonation =
System.Management.ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authority = "NTLMDOMAIN:IQ-HOME";
options.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope scope =
new ManagementScope(@"\\RTOKEN-SERVER\root\cimv2", options);
scope.Connect(); //checked its connected
// Make a connection to a remote computer.
// Replace the "FullComputerName" section of the
// string "\\\\FullComputerName\\root\\cimv2" with
// the full computer name or IP address of the
// remote computer.
ServiceController service = new ServiceController("Recharger Token", "RTOKEN-SERVER");
service.Refresh();
MessageBox.Show(service.Status.ToString()); //Error raised: {"Cannot open Service Control Manager on computer 'rToken-server'. This operation might require other privileges."}
}
請讓我知道我做錯了嗎? 我應該如何實現我的目標?
注意:我的開發PC是Windows 7 Ultimate,該服務基於Windows Server 2008 R2 Standard。 服務正在網絡服務下運行。 (我也將其更改為管理員登錄,但沒有運氣)
謝謝
嘗試使用此代碼,它使用您的ManagementScope,但是使用ManagementObjectSearcher通過我在注釋中提供的鏈接來查詢服務。
如果不是這樣,我將調查您的用戶是否有權執行您需要的操作。
private void WSControllerForm_Load(object sender, System.EventArgs e)
{
ConnectionOptions options = new ConnectionOptions();
options.Password = "password";
options.Username = "Administrator";
//i'm not 100% sure these 4 lines are needed - try without if it still fails
options.Impersonation =
System.Management.ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authority = "NTLMDOMAIN:RTOKEN-SERVER";
options.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope scope =
new ManagementScope(@"\\RTOKEN-SERVER\root\cimv2", options);
scope.Connect();
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher();
moSearcher.Scope = scope;
moSearcher.Query = new ObjectQuery("SELECT * FROM win32_Service WHERE Name ='Recharger Token'");
ManagementObjectCollection mbCollection = moSearcher.Get();
foreach (ManagementObject oReturn in mbCollection)
{
//invoke start
//ManagementBaseObject outParams = oReturn.InvokeMethod("StartService", null, null);
//invoke stop
//ManagementBaseObject outParams = oReturn.InvokeMethod("StopService", null, null);
//get result
//string a = outParams["ReturnValue"].ToString();
//get service state
string state = oReturn.Properties["State"].Value.ToString().Trim();
MessageBox.Show(state);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.