从非管理员用户帐户启动/停止 Windows 服务

发布于 2024-10-07 11:00:22 字数 250 浏览 7 评论 0原文

我有一个名为 BST 的 Windows 服务,我需要向非管理员用户 UserA 授予启动/停止此特定服务的权限。我的服务在各种 Windows 操作系统上运行,从 Windows Server 2003 到 Windows 7。

我该如何执行此操作?

我在 Google 上搜索并找到了一些有关使用命令 sc sdset 授予权限的内容,但我不太确定这些参数。我不想为组设置权限,而只想为特定用户(本例中为 UserA)设置权限。

I have a Windows service named, say, BST and I need to give a non-Administrator user, UserA, the permissions to Start/Stop this particular service. My service runs on a variety of Windows OS, starting from Windows Server 2003 to Windows 7.

How can I do this?

I Googled and found some stuff about giving permissions using the command sc sdset, but I am not exactly sure about the parameters. I do not want to set the permissions for a group, but ONLY to a particular user, UserA in this case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

燃情 2024-10-14 11:00:22

下面我整理了我学到的有关从非管理员用户帐户启动/停止 Windows 服务的所有内容,如果有人需要了解的话。

主要有两种方法可以启动/停止 Windows服务。
1.通过登录Windows用户帐户直接访问服务。
2. 使用网络服务帐户通过 IIS 访问服务。

启动/停止服务的命令行命令:

C:/> net start <SERVICE_NAME>
C:/> net stop <SERVICE_NAME>

启动/停止服务的 C# 代码:

ServiceController service = new ServiceController(SERVICE_NAME);

//Start the service
if (service.Status == ServiceControllerStatus.Stopped)
{
      service.Start();
      service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10.0));
}

//Stop the service
if (service.Status == ServiceControllerStatus.Running)
{
      service.Stop();
      service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10.0));
}

注 1:
通过 IIS 访问服务时,创建一个 Visual Studio C# ASP.NET Web 应用程序并将代码放入其中。将 WebService 部署到 IIS 根文件夹 (C:\inetpub\wwwroot\),然后就可以开始了。
通过 url http:/// 访问它。

1.直接访问方法

如果您发出命令或运行代码的 Windows 用户帐户是非管理员帐户,则您需要为该特定用户帐户设置权限,以便它能够启动和运行停止 Windows 服务。这就是你的做法。
登录到具有要从中启动/停止服务的非管理员帐户的计算机上的管理员帐户。打开命令提示符并发出以下命令:

C:/>sc sdshow <SERVICE_NAME>

此命令的输出将是像这样:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

它列出了该计算机上每个用户/组拥有的所有权限。

A description of one part of above command is as follows:

    D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)

It has the default owner, default group, and it has the Security descriptor control flags (A;;CCLCSWRPWPDTLOCRRC;;;SY):

ace_type - "A": ACCESS_ALLOWED_ACE_TYPE,
ace_flags - n/a,
rights - CCLCSWRPWPDTLOCRRC,  please refer to the Access Rights and Access Masks and Directory Services Access Rights
CC: ADS_RIGHT_DS_CREATE_CHILD - Create a child DS object.
LC: ADS_RIGHT_ACTRL_DS_LIST - Enumerate a DS object.
SW: ADS_RIGHT_DS_SELF - Access allowed only after validated rights checks supported by the object are performed. This flag can be used alone to perform all validated rights checks of the object or it can be combined with an identifier of a specific validated right to perform only that check.
RP: ADS_RIGHT_DS_READ_PROP - Read the properties of a DS object.
WP: ADS_RIGHT_DS_WRITE_PROP - Write properties for a DS object.
DT: ADS_RIGHT_DS_DELETE_TREE - Delete a tree of DS objects.
LO: ADS_RIGHT_DS_LIST_OBJECT - List a tree of DS objects.
CR: ADS_RIGHT_DS_CONTROL_ACCESS - Access allowed only after extended rights checks supported by the object are performed. This flag can be used alone to perform all extended rights checks on the object or it can be combined with an identifier of a specific extended right to perform only that check.
RC: READ_CONTROL - The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). (This is a Standard Access Right, please read more http://msdn.microsoft.com/en-us/library/aa379607(VS.85).aspx)
object_guid - n/a,
inherit_object_guid - n/a,
account_sid - "SY": Local system. The corresponding RID is SECURITY_LOCAL_SYSTEM_RID.

现在我们需要做的是为我们想要的组或用户设置启动/停止 Windows 服务的适当权限。在这种情况下,我们需要当前的非管理员用户能够启动/停止服务,因此我们将设置该用户的权限。为此,我们需要该特定 Windows 用户帐户的 SID。要获取它,请打开注册表(“开始”>“regedit”)并找到以下注册表项。

LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

在此之下,该计算机中的每个用户帐户都有一个单独的密钥,密钥名称是每个帐户的 SID。 SID 的格式通常为 S-1-5-21-2103278432-2794320136-1883075150-1000。单击每个键,您将在右侧窗格中看到每个键的值列表。找到“ProfileImagePath”,通过它的值可以找到SID所属的用户名。例如,如果帐户的用户名是 SACH,则“ProfileImagePath”的值将类似于“C:\Users\Sach”。因此,请记下您要为其设置权限的用户帐户的 SID。

注2:
这是一个简单的 C# 代码示例,可用于获取所述键及其值的列表。

//LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList RegistryKey
RegistryKey profileList = Registry.LocalMachine.OpenSubKey(keyName);

//Get a list of SID corresponding to each account on the computer
string[] sidList = profileList.GetSubKeyNames();

foreach (string sid in sidList)
{
    //Based on above names, get 'Registry Keys' corresponding to each SID
    RegistryKey profile = Registry.LocalMachine.OpenSubKey(Path.Combine(keyName, sid));

    //SID
    string strSID = sid;
    //UserName which is represented by above SID    
    string strUserName = (string)profile.GetValue("ProfileImagePath");
}

现在我们已经有了要设置权限的用户帐户的 SID,让我们开始吧。假设用户帐户的 SID 为 S-1-5-21-2103278432-2794320136-1883075150-1000
将 [sc sdshow ] 命令的输出复制到文本编辑器。它看起来像这样:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

现在,复制上述文本的 (A;;CCLCSWRPWPDTLOCRRC;;;SY) 部分,并将其粘贴到 S 之前 :(AU;... 文本的一部分。然后将该部分更改为如下所示:
(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)

然后在前面添加sc sdset ,并将上面的内容括起来带引号的部分。您的最终命令应如下所示:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

现在在命令提示符中执行此命令,如果成功,它应提供如下输出:

[SC] SetServiceObjectSecurity SUCCESS

现在我们可以开始了!您的非管理员用户帐户已被授予启动/停止您的服务的权限!尝试登录到用户帐户并启动/停止服务,它应该可以让您执行此操作。

2.通过IIS方式访问

本例中,我们需要将权限授予IIS用户“网络服务”,而不是登录Windows用户帐户。过程是一样的,只是命令的参数会改变。由于我们将权限设置为“网络服务”,因此在我们之前使用的最终 sdset 命令中将 SID 替换为字符串“NS”。最终命令应如下所示:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;NS)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

从管理员用户帐户在命令提示符中执行它,瞧!您有权使用 WebMethod 从任何用户帐户(无论是否为管理员帐户)启动/停止服务。请参阅注释 1 了解如何执行此操作。

Below I have put together everything I learned about Starting/Stopping a Windows Service from a non-Admin user account, if anyone needs to know.

Primarily, there are two ways in which to Start / Stop a Windows Service.
1. Directly accessing the service through logon Windows user account.
2. Accessing the service through IIS using Network Service account.

Command line command to start / stop services:

C:/> net start <SERVICE_NAME>
C:/> net stop <SERVICE_NAME>

C# Code to start / stop services:

ServiceController service = new ServiceController(SERVICE_NAME);

//Start the service
if (service.Status == ServiceControllerStatus.Stopped)
{
      service.Start();
      service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10.0));
}

//Stop the service
if (service.Status == ServiceControllerStatus.Running)
{
      service.Stop();
      service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10.0));
}

Note 1:
When accessing the service through IIS, create a Visual Studio C# ASP.NET Web Application and put the code in there. Deploy the WebService to IIS Root Folder (C:\inetpub\wwwroot\) and you're good to go.
Access it by the url http:///.

1. Direct Access Method

If the Windows User Account from which either you give the command or run the code is a non-Admin account, then you need to set the privileges to that particular user account so it has the ability to start and stop Windows Services. This is how you do it.
Login to an Administrator account on the computer which has the non-Admin account from which you want to Start/Stop the service. Open up the command prompt and give the following command:

C:/>sc sdshow <SERVICE_NAME>

Output of this will be something like this:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

It lists all the permissions each User / Group on this computer has with regards to .

A description of one part of above command is as follows:

    D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)

It has the default owner, default group, and it has the Security descriptor control flags (A;;CCLCSWRPWPDTLOCRRC;;;SY):

ace_type - "A": ACCESS_ALLOWED_ACE_TYPE,
ace_flags - n/a,
rights - CCLCSWRPWPDTLOCRRC,  please refer to the Access Rights and Access Masks and Directory Services Access Rights
CC: ADS_RIGHT_DS_CREATE_CHILD - Create a child DS object.
LC: ADS_RIGHT_ACTRL_DS_LIST - Enumerate a DS object.
SW: ADS_RIGHT_DS_SELF - Access allowed only after validated rights checks supported by the object are performed. This flag can be used alone to perform all validated rights checks of the object or it can be combined with an identifier of a specific validated right to perform only that check.
RP: ADS_RIGHT_DS_READ_PROP - Read the properties of a DS object.
WP: ADS_RIGHT_DS_WRITE_PROP - Write properties for a DS object.
DT: ADS_RIGHT_DS_DELETE_TREE - Delete a tree of DS objects.
LO: ADS_RIGHT_DS_LIST_OBJECT - List a tree of DS objects.
CR: ADS_RIGHT_DS_CONTROL_ACCESS - Access allowed only after extended rights checks supported by the object are performed. This flag can be used alone to perform all extended rights checks on the object or it can be combined with an identifier of a specific extended right to perform only that check.
RC: READ_CONTROL - The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). (This is a Standard Access Right, please read more http://msdn.microsoft.com/en-us/library/aa379607(VS.85).aspx)
object_guid - n/a,
inherit_object_guid - n/a,
account_sid - "SY": Local system. The corresponding RID is SECURITY_LOCAL_SYSTEM_RID.

Now what we need to do is to set the appropriate permissions to Start/Stop Windows Services to the groups or users we want. In this case we need the current non-Admin user be able to Start/Stop the service so we are going to set the permissions to that user. To do that, we need the SID of that particular Windows User Account. To obtain it, open up the Registry (Start > regedit) and locate the following registry key.

LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Under that there is a seperate Key for each an every user account in this computer, and the key name is the SID of each account. SID are usually of the format S-1-5-21-2103278432-2794320136-1883075150-1000. Click on each Key, and you will see on the pane to the right a list of values for each Key. Locate "ProfileImagePath", and by it's value you can find the User Name that SID belongs to. For instance, if the user name of the account is SACH, then the value of "ProfileImagePath" will be something like "C:\Users\Sach". So note down the SID of the user account you want to set the permissions to.

Note2:
Here a simple C# code sample which can be used to obtain a list of said Keys and it's values.

//LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList RegistryKey
RegistryKey profileList = Registry.LocalMachine.OpenSubKey(keyName);

//Get a list of SID corresponding to each account on the computer
string[] sidList = profileList.GetSubKeyNames();

foreach (string sid in sidList)
{
    //Based on above names, get 'Registry Keys' corresponding to each SID
    RegistryKey profile = Registry.LocalMachine.OpenSubKey(Path.Combine(keyName, sid));

    //SID
    string strSID = sid;
    //UserName which is represented by above SID    
    string strUserName = (string)profile.GetValue("ProfileImagePath");
}

Now that we have the SID of the user account we want to set the permissions to, let's get down to it. Let's assume the SID of the user account is S-1-5-21-2103278432-2794320136-1883075150-1000.
Copy the output of the [sc sdshow ] command to a text editor. It will look like this:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

Now, copy the (A;;CCLCSWRPWPDTLOCRRC;;;SY) part of the above text, and paste it just before the S:(AU;... part of the text. Then change that part to look like this:
(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)

Then add sc sdset at the front, and enclose the above part with quotes. Your final command should look something like the following:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Now execute this in your command prompt, and it should give the output as follows if successful:

[SC] SetServiceObjectSecurity SUCCESS

Now we're good to go! Your non-Admin user account has been granted permissions to Start/Stop your service! Try loggin in to the user account and Start/Stop the service and it should let you do that.

2. Access through IIS Method

In this case, we need to grant the permission to the IIS user "Network Services" instead of the logon Windows user account. The procedure is the same, only the parameters of the command will be changed. Since we set the permission to "Network Services", replace SID with the string "NS" in the final sdset command we used previously. The final command should look something like this:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;NS)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Execute it in the command prompt from an Admin user account, and voila! You have the permission to Start / Stop the service from any user account (irrespective of whether it ia an Admin account or not) using a WebMethod. Refer to Note1 to find out how to do so.

椒妓 2024-10-14 11:00:22

我使用 SubInACL 实用程序用于此目的。例如,如果我想为计算机 VMX001 上的用户作业提供启动和停止万维网发布服务(也称为 w3svc)的能力,我会以管理员身份发出以下命令:

subinacl.exe /service w3svc /grant=VMX001\job=PTO

您可以授予的权限定义如下(列表取自 此处):

F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
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

因此,通过指定 PTO,我有权 job 用户暂停/继续、启动和停止 w3svc 服务。


编辑更新了 web.archive.org 的链接,因为原始的 MS 链接已失效。

I use the SubInACL utility for this. For example, if I wanted to give the user job on the computer VMX001 the ability to start and stop the World Wide Web Publishing Service (also know as w3svc), I would issue the following command as an Administrator:

subinacl.exe /service w3svc /grant=VMX001\job=PTO

The permissions you can grant are defined as follows (list taken from here):

F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
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

So, by specifying PTO, I am entitling the job user to Pause/Continue, Start, and Stop the w3svc service.


Edit: updated links to web.archive.org since the original MS links are dead.

我的奇迹 2024-10-14 11:00:22
  1. 以管理员身份登录。
  2. 从 Microsoft 下载 subinacl.exe
    http://www.microsoft.com/en-us/download/details.aspx? id=23510
  3. 授予普通用户帐户管理 BST 的权限
    服务。
    subinacl.exe 位于 C:\Program Files (x86)\Windows Resource Kits\Tools\)。
  4. cd C: \Program Files (x86)\Windows Resource Kits\Tools\
    subinacl /SERVICE \\MachineName\bst /GRANT=domainname.com\username=F
    subinacl /SERVICE \\MachineName\bst /GRANT=username=F
  5. 注销并以用户身份重新登录。他们现在应该能够
    启动BST服务。
  1. Login as an administrator.
  2. Download subinacl.exe from Microsoft:
    http://www.microsoft.com/en-us/download/details.aspx?id=23510
  3. Grant permissions to the regular user account to manage the BST
    services.
    (subinacl.exe is in C:\Program Files (x86)\Windows Resource Kits\Tools\).
  4. cd C:\Program Files (x86)\Windows Resource Kits\Tools\
    subinacl /SERVICE \\MachineName\bst /GRANT=domainname.com\username=F or
    subinacl /SERVICE \\MachineName\bst /GRANT=username=F
  5. Logout and log back in as the user. They should now be able to
    launch the BST service.
玩物 2024-10-14 11:00:22

有一个免费的 GUI 工具ServiceSecurityEditor

它允许您编辑 Windows 服务权限。我已成功使用它来授予非管理员用户启动和停止服务的权限。

在我知道这个工具之前,我曾使用过“sc sdset”。

ServiceSecurityEditor 感觉就像作弊,就这么简单:)

There is a free GUI Tool ServiceSecurityEditor

Which allows you to edit Windows Service permissions. I have successfully used it to give a non-Administrator user the rights to start and stop a service.

I had used "sc sdset" before I knew about this tool.

ServiceSecurityEditor feels like cheating, it's that easy :)

诠释孤独 2024-10-14 11:00:22

使用以下工具之一向服务授予管理权限要容易得多:

  • 组策略
  • 安全模板
  • subinacl.exe 命令行工具。

以下是 MSKB 文章,其中包含适用于 Windows Server 2008 的说明/ Windows 7,但 2000 和 2003 的说明相同。

It's significantly easier to grant management permissions to a service using one of these tools:

  • Group Policy
  • Security Template
  • subinacl.exe command-line tool.

Here's the MSKB article with instructions for Windows Server 2008 / Windows 7, but the instructions are the same for 2000 and 2003.

何时共饮酒 2024-10-14 11:00:22

subinacl.exe 命令行工具可能是本文中唯一可行且非常易于使用的工具。您不能将 GPO 与非系统服务一起使用,而另一个选项则过于复杂。

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

狼性发作 2024-10-14 11:00:22

这是一个批处理文件,它自动执行授予特定用户或组权限以停止和启动特定 Windows 服务所涉及的任务。它使用Windows内置命令sc.exewmic.exe,因此不依赖于任何外部工具。

批处理文件有 5 个退出代码来帮助自动化过程:

  • -1 批处理文件意外退出。
  • 0 批处理文件成功完成。
  • 1 获取用户SID失败。
  • 2 获取当前服务权限失败。
  • 3 无法设置服务的新权限。

在运行批处理文件之前,请确保替换以下变量中的值以匹配您的环境:

设置“$ServiceName=TestService”

设置“$UserName=TestUser”

Set "$UserDomain=MyDomain"

注意:批处理文件没有任何错误检查,例如,它不会检查服务是否确实存在,或者用户是否存在已被授予该服务的适当权限。

@Echo Off & Cls
SetLocal EnableExtensions EnableDelayedExpansion
Set "$ExitCode=-1"

Set "$ServiceName=TestService"
Set "$UserName=TestUser"
Set "$UserDomain=MyDomain"

Call :GetUserSID "!$UserDomain!" "!$UserName!" && (
 Call :ServiceGetPermissions "!$ServiceName!" && (
  Set "$ServicePermissions=!$ServicePermissions:)S:(=)@:(!"
  For /f "Tokens=1 Delims=@" %%x In ("!$ServicePermissions!") Do Set "$ServicePermissions=%%x"
  Set "$ServicePermissions=!$ServicePermissions!(A;;RPWPCR;;;!$UserSID!)"
  Call :ServiceSetPermissions "!$ServiceName!" "!$ServicePermissions!" && Set "$ExitCode=0" || Set "$ExitCode=3"
 ) || (
  Set "$ExitCode=2"
 )
) || (
 Set "$ExitCode=1"
)
Exit /b !$ExitCode!

:GetUserSID <UserDomain> <UserAccount>
:-------------------------------------
Set "#GetUserSID=-1"
Set "#UserDomain=%~1"
Set "#UserAccount=%~2"
Set "$UserSID="
For /f "Skip=1 Tokens=1" %%x In ('2^>Nul wmic.exe UserAccount Where ^(Name^="!#UserAccount!" And Domain^="!#UserDomain!"^) Get SID') Do (
 If Not Defined $UserSID Set "$UserSID=%%x"
 If /I Not "!$UserSID:~0,6!"=="S-1-5-" Set "$UserSID="
)
If Defined $UserSID Set "#GetUserSID=0" Else Set #GetUserSID=2"
Exit /b !#GetUserSID!

:ServiceGetPermissions <ServiceName>
:-----------------------------------
Set "#ServiceGetPermissions=-1"
Set "#ServiceName=%~1"
Set "$ServicePermissions="
For /f "Skip=1 Tokens=1" %%x In ('2^>Nul sc.exe sdshow "!#ServiceName!"') Do Set "$ServicePermissions=%%x"
If Defined $ServicePermissions Set "#ServiceGetPermissions=0" Else Set "#ServiceGetPermissions=3"
Exit /b !#ServiceGetPermissions!

:ServiceSetPermissions <ServiceName> <ServicePermissions>
:--------------------------------------------------------
Set "#ServiceSetPermissions=-1"
Set "#ServiceName=%~1"
Set "#ServicePermissions=%~2"
>Nul 2>&1 sc.exe sdset "!#ServiceName!" "!#ServicePermissions!" && Set "#ServiceSetPermissions=0" || Set "#ServiceSetPermissions=5"
Exit /b !#ServiceSetPermissions!

Here is a batch file that automates the tasks involved in granting a specific user or group permissions to stop and start a specific windows services. It uses the Windows built-in commands sc.exe and wmic.exe, so there are no dependencies on any external tools.

The batch file has 5 exit codes to help in automation processes:

  • -1 Batch file exited unexpectedly.
  • 0 Batch file completed successfully.
  • 1 Failed to get user SID.
  • 2 Failed to get current service permissions.
  • 3 Failed to set the new permissions on the service.

Before you run the batch file, make sure you replace the values in the following variable to match your environment:

Set "$ServiceName=TestService"

Set "$UserName=TestUser"

Set "$UserDomain=MyDomain"

Note: The batch file does not have any error checking, for example, it does not check if the services actually exists, or if the user was already granted the proper permissions on the service.

@Echo Off & Cls
SetLocal EnableExtensions EnableDelayedExpansion
Set "$ExitCode=-1"

Set "$ServiceName=TestService"
Set "$UserName=TestUser"
Set "$UserDomain=MyDomain"

Call :GetUserSID "!$UserDomain!" "!$UserName!" && (
 Call :ServiceGetPermissions "!$ServiceName!" && (
  Set "$ServicePermissions=!$ServicePermissions:)S:(=)@:(!"
  For /f "Tokens=1 Delims=@" %%x In ("!$ServicePermissions!") Do Set "$ServicePermissions=%%x"
  Set "$ServicePermissions=!$ServicePermissions!(A;;RPWPCR;;;!$UserSID!)"
  Call :ServiceSetPermissions "!$ServiceName!" "!$ServicePermissions!" && Set "$ExitCode=0" || Set "$ExitCode=3"
 ) || (
  Set "$ExitCode=2"
 )
) || (
 Set "$ExitCode=1"
)
Exit /b !$ExitCode!

:GetUserSID <UserDomain> <UserAccount>
:-------------------------------------
Set "#GetUserSID=-1"
Set "#UserDomain=%~1"
Set "#UserAccount=%~2"
Set "$UserSID="
For /f "Skip=1 Tokens=1" %%x In ('2^>Nul wmic.exe UserAccount Where ^(Name^="!#UserAccount!" And Domain^="!#UserDomain!"^) Get SID') Do (
 If Not Defined $UserSID Set "$UserSID=%%x"
 If /I Not "!$UserSID:~0,6!"=="S-1-5-" Set "$UserSID="
)
If Defined $UserSID Set "#GetUserSID=0" Else Set #GetUserSID=2"
Exit /b !#GetUserSID!

:ServiceGetPermissions <ServiceName>
:-----------------------------------
Set "#ServiceGetPermissions=-1"
Set "#ServiceName=%~1"
Set "$ServicePermissions="
For /f "Skip=1 Tokens=1" %%x In ('2^>Nul sc.exe sdshow "!#ServiceName!"') Do Set "$ServicePermissions=%%x"
If Defined $ServicePermissions Set "#ServiceGetPermissions=0" Else Set "#ServiceGetPermissions=3"
Exit /b !#ServiceGetPermissions!

:ServiceSetPermissions <ServiceName> <ServicePermissions>
:--------------------------------------------------------
Set "#ServiceSetPermissions=-1"
Set "#ServiceName=%~1"
Set "#ServicePermissions=%~2"
>Nul 2>&1 sc.exe sdset "!#ServiceName!" "!#ServicePermissions!" && Set "#ServiceSetPermissions=0" || Set "#ServiceSetPermissions=5"
Exit /b !#ServiceSetPermissions!
往日 2024-10-14 11:00:22

Windows 服务使用本地系统帐户运行。它可以在用户登录系统时自动启动,也可以手动启动。但是,Windows 服务说 BST 可以使用计算机上的特定用户帐户运行。这可以完成如下所示:启动 services.msc 并转到 Windows 服务的属性,BST。从那里您可以提供所需用户的登录参数。然后服务使用该用户帐户运行,并且其他用户无法运行该服务。

Windows Service runs using a local system account.It can start automatically as the user logs into the system or it can be started manually.However, a windows service say BST can be run using a particular user account on the machine.This can be done as follows:start services.msc and go to the properties of your windows service,BST.From there you can give the login parameters of the required user.Service then runs with that user account and no other user can run that service.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文