c# Granting “Log On As Service” permission to a windows user

二次信任 提交于 2019-12-20 18:34:21

问题


how do I grant a user the LogOnAsService right for a service?

I need to do this manually, in the services.msc app I can go to the service, change the password (setting the same that there was before), click apply and I get a message:

The account .\postgres has been granted the Log On As Service right.

How do I do this from code, because otherwise I have to give this permission by hand each time I run the application and this is not a possibility

@Steve

    static void Main()
    {
        // irrelevant stuff

        GrantLogonAsServiceRight("postgres");

        // irrelevant stuff
    }

    private static void GrantLogonAsServiceRight(string username)
    {
        using (LsaWrapper lsa = new LsaWrapper())
        {
            lsa.AddPrivileges(username, "SeServiceLogonRight");
        }
    }

and the LSA lib by this guy Willy.


回答1:


See Granting User Rights in C#.

You have to invoke the LSA APIs via P/Invoke, and that URL has a reference to a wrapper class that does that for you. So the code you end up with is simple:

private static void GrantLogonAsServiceRight(string username)
{
   using (LsaWrapper lsa = new LsaWrapper())
   {
      lsa.AddPrivileges(username, "SeServiceLogonRight");
   }
}


来源:https://stackoverflow.com/questions/3891623/c-sharp-granting-log-on-as-service-permission-to-a-windows-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!