简体   繁体   中英

C# / .Net: Run CMD as admin with provided credentials

i searched for this some hours today but i only find solutions that wont work. Maybe it is impossible but let's give it a try:

I'm in a company and I will write some code so that a user can run the software whenever he need it. The software needs administrator-permissions. For example I've wrote some code to start the cmd as admin and create a folder at c:/Windows (you'll need admin-permission for that). The credentials for the admin account are right (we use Microsoft AD) but I only get "Access denied" in the cmd. Does anyone know whether it is possible to get admin permission with hard coded credentials?

Note: Don't talk about security risks, the cmd is not the target software but it should demonstrate the problem.

My code:

Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = @"/Kmkdir C:\Windows\_Test";
p.StartInfo.UserName = "admin";
System.Security.SecureString sPW = new System.Security.SecureString();
sPW.AppendChar('a');
sPW.AppendChar('b');
sPW.AppendChar('c');
p.StartInfo.Password = sPW;
p.StartInfo.UseShellExecute = false;
p.Start();

You are still getting an error because all admin accounts in newer windows versions (since Vista) technically are standard user accounts. The way administrative tasks are performed is through the User Account Control (UAC). It allows you to elevate permissions as administrator to perform administrative tasks. So yes, you are executing the process using an administrator account, but you did not elevate the process. To do so, add this parameter:

p.StartInfo.Verb = "runas";
p.StartInfo.UseShellExecute = true;

You can remove all other parameters regarding authentication, since all the authentication is handled by UAC. If for some reason you wish not to use UAC, then you probably will have to disable it, which is not recommended in most cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM