Asp.net
如何從 ASP.NET 應用程序啟動/停止 Windows 服務 - 安全問題
這是我的 Windows/.NET 安全堆棧:
- 在 Windows Server 2003 機器上作為 LocalSystem 執行的 Windows 服務。
- 一個 .NET 3.5 網站在同一個盒子上執行,在“預設”生產伺服器 IIS 設置下(所以可能是 NETWORKSERVICE 使用者?)
在我的預設 VS2008 DEV 環境中,我有一個方法,它從 ASP.NET 應用程序中呼叫,效果很好:
private static void StopStartReminderService() { ServiceController svcController = new ServiceController("eTimeSheetReminderService"); if (svcController != null) { try { svcController.Stop(); svcController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); svcController.Start(); } catch (Exception ex) { General.ErrorHandling.LogError(ex); } } }當我在生產伺服器上執行它時,我從 ServiceController 收到以下錯誤:
來源:System.ServiceProcess -> System.ServiceProcess.ServiceController -> IntPtr GetServiceHandle(Int32) -> System.InvalidOperationException 消息:無法在電腦“.”上打開 eTimeSheetReminderService 服務。
為什麼會發生這種情況,我該如何解決?
編輯:
答案如下,主要在評論中,但要澄清:
- 該問題與安全相關,並且由於 NETWORKSERVICE 帳戶沒有足夠的權限來啟動/停止服務
- 我創建了一個本地使用者帳戶,並將其添加到 PowerUsers 組(該組幾乎具有管理員權限)
- 我不希望我的整個 Web 應用程序一直模擬那個使用者,所以我只在我操作服務的方法中模擬。我通過使用以下資源來幫助我在程式碼中做到這一點:
**注意:**我不通過 web.config 進行模擬,而是在程式碼中進行。請參閱上面的 MS 知識庫文章。
嘗試將此添加到您的 Web.Config。
<identity impersonate="true"/>
授予 IIS 啟動/停止特定服務的權限:
- 下載並安裝Subinacl.exe。(一定要獲取最新版本!部分資源包中分發的早期版本不起作用!)
- 發出類似於以下的命令:
subinacl /service {yourServiceName} /grant=IIS_WPG=F這將對該特定服務的完整服務控制權限授予內置 IIS_WPG 組。(這適用於 IIS6 / Win2k3。)YMMV 用於更新版本的 IIS。)