如何使用 Powershell 授予远程启动/停止服务的权限?

spl*_*its 10 powershell windows-service

我们有一个 PowerShell 脚本,可以在另一台计算机上重新启动服务。当我们使用 PowerShell 的内置服务控制 cmdlet 时,像这样:

$svc = Get-Service -Name MyService -ComputerName myservicehostname
Stop-Service -InputObject $svc
Start-Service -InputObject $svc
Run Code Online (Sandbox Code Playgroud)

我们得到这个错误:

停止服务:无法在计算机“myservicehostname”上打开 MyService 服务。

但是,当我们使用 sc.exe 时,像这样:

C:\Windows\System32\sc \\myservicehostname stop MyService
C:\Windows\System32\sc \\myservicehostname start MyService
Run Code Online (Sandbox Code Playgroud)

启动和停止成功。

重新启动的用户不是管理员。我们使用 subinacl 授予用户启动/停止和查询服务的权限:

subinacl.exe /service MyService /GRANT=MyServiceControlUser=STO
Run Code Online (Sandbox Code Playgroud)

为什么 PowerShell 不能停止我的服务但sc.exe可以?

spl*_*its 20

事实证明我没有给予足够的权限subinacl。授予操作的可能访问值为:

    F : Full Control  
    R : Generic Read  
    W : Generic Write  
    X : Generic eXecute  
  or any following values  
    L : Read controL  
    Q : Query Service Configuration  
    S : Query Service Status  
    E : Enumerate Dependent Services  
    C : Service Change Configuration  
    T : Start Service  
    O : Stop Service  
    P : Pause/Continue Service  
    I : Interrogate Service  
    U : Service User-Defined Control Commands  
Run Code Online (Sandbox Code Playgroud)

我使用了S(查询服务状态)、T(启动服务)和O(停止服务)。 我还需要 E(枚举相关服务)。 PowerShell cmdlet 似乎在启动/停止时需要查看相关服务。

这是我更新的subinacl命令:

subinacl.exe /service MyService /GRANT=MyServiceControlUser=STOE
Run Code Online (Sandbox Code Playgroud)

如果您不想下载/使用subinacl.exe,您可以通过Carbon模块的Grant-ServiceControlPermissionGrant-ServicePermission函数使用 PowerShell 。(免责声明:我是 Carbon 项目的所有者/维护者。)