c# Granting "Log On As Service" permission to a windows user
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, becaus开发者_StackOverflow社区e 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.
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");
}
}
精彩评论