【发布时间】:2008-12-18 14:38:02
【问题描述】:
我有一个运行良好的 Windows 服务,但我必须让它在一个特殊的用户帐户下运行。
目前我进入服务并更改登录为部分,但对于部署,这必须更专业地完成。
有没有办法让我以编程方式或在服务安装过程中以自定义用户帐户身份登录?
【问题讨论】:
标签: windows-services installation service
我有一个运行良好的 Windows 服务,但我必须让它在一个特殊的用户帐户下运行。
目前我进入服务并更改登录为部分,但对于部署,这必须更专业地完成。
有没有办法让我以编程方式或在服务安装过程中以自定义用户帐户身份登录?
【问题讨论】:
标签: windows-services installation service
当您打开服务控制管理器(SCM)时,当然会有一个标有登录的选项卡。在其中您可以指定它应该在哪个域或机器帐户下运行...
但是以编程方式。如果您在代码中使用 Service Installer 类,则可以在此处指定它..
public class MyServiceInstaller : Installer
{
private ServiceInstaller servInst;
private ServiceProcessInstaller servProcInst;
public MyServiceInstaller () { InitializeComponent(); }
#region Component Designer generated code
private void InitializeComponent()
{
servInst = new ServiceInstaller();
servProcInst = new ServiceProcessInstaller();
// -----------------------------------------------
servProcInst.Account = ServiceAccount.LocalSystem; // or whatever accnt you want
servProcInst.Username = null; // or, specify a specifc acct here
servProcInst.Password = null;
servProcInst.AfterInstall +=
new InstallEventHandler(this.AfterServProcInstall);
servInst.ServiceName = "MyService";
servInst.DisplayName = "Display name for MyService";
servInst.Description = " Description for my service";
servInst.StartType = ServiceStartMode.Automatic;
servInst.AfterInstall +=
new InstallEventHandler(this.AfterServiceInstall);
Installers.AddRange(new Installer[] { servProcInst, servInst });
}
#endregion
}
private void AfterServiceInstall(object sender, InstallEventArgs e) { }
private void AfterServProcInstall(object sender, InstallEventArgs e) { }
【讨论】:
查看CreateService 函数,尤其是lpServiceStartName 参数。那是“应该运行服务的帐户的名称。”
【讨论】:
你是如何安装的?这是一个 .net 服务吗(在这种情况下,我认为您可以在安装程序对象上指定帐户)。
通常,安装程序技术允许您更改凭据(COM 的服务注册可能除外)
如果您正在执行 xcopy 注册,然后在第一次运行时注册,您可以使用 ChangeServiceConfig(..., ServiceName, Password,...) 来修复注册。
【讨论】:
遇到这个,我想我也会加入一个 Powershell 选项,因为我很方便,它可以帮助某人:
$svc = gwmi win32_service -computername <computer name> -filter "name='<name of your service>'"
$inParams = $svc.psbase.getMethodParameters("change")
$inParams["StartName"] = '<domain\username>'
$inParams["StartPassword"] = '<password>'
$null = $svc.invokeMethod("change", $inParams, $null)
【讨论】: