简体   繁体   English

以管理员身份运行命令行程序

[英]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 这是方法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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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