Run part of a c# program with admin privileges

£可爱£侵袭症+ 提交于 2019-12-08 19:32:14

问题


Is there a way to request elevated privileges from the os, for "just a part" of a c# program?

I'm writing a bunch of integrationtests using NUnit. One of the things I'm testing is if the application under test correctly connects to port 843. The test opens a listening socket at port 843, and then throws all sorts of responses to the application under test, and verifies if the application behaves correctly.

Opening a listening socket on port 843 requires admin privileges however.

I'd like to find the least intrusive way to be able to run this test. I could run the entire NUnit suite as root/admin, but that would make a lot of stuff run as root, that really doesn't need to be ran as root, which I'd like to prevent.


回答1:


Nope. Elevation is all or nothing. Typically if elevation is required, the app bootstraps itself into an elevated state.




回答2:


If required below code would help you to find out if the current logged in user is admin or not:

using System;
using System.Security.Principal; 

class Test
{
    public static void Main()
    {
        if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
        {
            Console.WriteLine("I am an admin.");
        }
    }
}



回答3:


Yes, you could take a look at the LogonUser function. Here's a sample.




回答4:


A process has to be started with elevated privileges to have elevated rights. You cannot change your elevated status "in process".

A way to work around this is to do as Task Manager. If you run that "unelevated" and click on "Show processes for all users", it basically kills of the old task manager process and starts a new one with elevated privileges in order to do the job.



来源:https://stackoverflow.com/questions/2271656/run-part-of-a-c-sharp-program-with-admin-privileges

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