Mgr.CreateService
(code;调用 CreateServiceW
),但它没有出现在 services.msc 中。
get-service
中,并且 net start
可以工作。
如何让它出现在 services.msc 中?
编辑:比较 Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service 中的两个条目:
- Mine: "Start"=dword:00000003
- Theirs: "Start"=dword:00000002
- Mine: "ErrorControl"=dword:00000000
- Theirs: "ErrorControl"=dword:00000001
- Mine: <missing value>
- Theirs: "DependOnService"=hex(7):52,00,50,00,43,00,53,00,53,00,00,00,00,00
- Mine: "ObjectName"="LocalSystem"
- Theirs: "ObjectName"="NT AUTHORITY\\NetworkService"
所以我认为正在发生的是它需要有一个与上面匹配的ObjectName? - 与 DependOnService 有关吗[它们的值:RPCSS;我相信这是远程过程调用 Windows 服务]?
编辑1:
//go:build windows
package mypackage
import (
"fmt"
"path/filepath"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"
)
func windowsServiceInstall(name, binary, cliArgs string) error {
var err error
var m *mgr.Mgr
if m, err = mgr.Connect(); err != nil {
return err
}
defer func(m *mgr.Mgr) {
if err = m.Disconnect(); err != nil {
panic(err)
}
}(m)
var service *mgr.Service
if service, err = m.OpenService(name); err == nil {
if err = service.Close(); err != nil {
return err
}
return fmt.Errorf("service %s already exists", name)
}
if service, err = m.CreateService(
name,
binary,
mgr.Config{DisplayName: name,
BinaryPathName: fmt.Sprintf("%s %s", binary, cliArgs),
},
"is", "auto-started",
); err != nil {
return err
}
defer func(service *mgr.Service) {
if e := service.Close(); e != nil {
panic(e)
}
}(service)
if err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info); err != nil {
if e := service.Delete(); e != nil {
return e
}
return fmt.Errorf("SetupEventLogSource() failed: %s", err)
}
return nil
}
可能缺少服务依赖项或创建服务的调用配置不正确。 如果您的服务依赖于其他服务才能正常运行,则必须在创建服务时指定这些依赖项。您可以使用 mgr.Service 对象的 SetDependency 方法来执行此操作。例如:
dependencies := []string{"RPCSS"} // Add here the necessary dependencies for your service
if err = service.SetDependencies(dependencies); err != nil {
return err
}
您可以尝试将您的服务配置为现有服务,看看它是否出现:
if service, err = m.CreateService(
name,
binary,
mgr.Config{
DisplayName: name,
BinaryPathName: fmt.Sprintf("%s %s", binary, cliArgs),
StartType: mgr.StartAutomatic,
ErrorControl: windows.SERVICE_ERROR_NORMAL,
ServiceStartName: "NT AUTHORITY\\NetworkService", // Set the ServiceStartName to NT AUTHORITY\\NetworkService
},
"is", "auto-started",
); err != nil {
return err
}