简体   繁体   中英

Run a command line program as Administrator

I need to run this as an administrator

string cname = Environment.UserDomainName + "\\" + Environment.UserName;
string resetTrust = "netdom /resetpwd /s:server01 /ud:" + cname + "/pd:" + textBoxPassword.Text.Trim();
String output = ExecuteCommandAsAdmin(resetTrust);
MessageBox.Show(output);

Here is the method ExecuteCommandAsAdmin

public static string ExecuteCommandAsAdmin(string command)
{
    string cname = Environment.UserDomainName + "\\" + Environment.UserName;

    ProcessStartInfo procStartInfo = new ProcessStartInfo()
    {
        RedirectStandardError = true,
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = true,
        FileName = "runas.exe",
        Arguments = "/user:" + cname + "\"cmd /K " + command + "\""
    };

    using (Process proc = new Process())
    {
        proc.StartInfo = procStartInfo;
        proc.Start();

        string output = proc.StandardOutput.ReadToEnd();

        if (string.IsNullOrEmpty(output))
            output = proc.StandardError.ReadToEnd();

        return output;
    }
}

If you know a better way to do this, please let me know. I am not storing the password. Just passing it so it can be executed. If the wrong person enters the wrong password, nothing happens since they aren't an Admin.

Thank You

使用runas /user:name@domain cmd

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