如何使用提升的凭据在 C#(在网络服务器上)中 运行 shell 命令?

How do I run a shell command in C# (on a webserver) with elevated credentials?

我有一个 Web 服务,我希望能够 运行 需要管理员权限的 shell 命令。 (命令为DJOIN,用电脑账号预置AD并创建文件。)

我正在测试如下:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Security.SecureString ssPwd = new System.Security.SecureString();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/C echo %username% > c:\test\user.txt";
proc.StartInfo.Domain = "mydomain";
proc.StartInfo.UserName = "myadmin";
string password = "mypassword";
for (int x = 0; x < password.Length; x++)
{
    ssPwd.AppendChar(password[x]);
}
proc.StartInfo.Password = ssPwd;
proc.Start();

Web 服务器上的 c:\test 文件夹具有正确的权限,如果我 运行 没有指定凭据,代码块 运行 没问题。但是,当我添加它们时它失败了。

我也试过包括:

proc.StartInfo.Verb = "runas"

但这也不起作用。

如何 运行 作为高级用户执行命令?

我的工作方式是使用以下代码:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Security.SecureString ssPwd = new System.Security.SecureString();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/C echo %username% > c:\test\user.txt";
proc.StartInfo.Domain = "mydomain";
proc.StartInfo.Verb = "runas";
proc.StartInfo.UserName = "myadmin";
string password = "mypassword";
for (int x = 0; x < password.Length; x++)
{
    ssPwd.AppendChar(password[x]);
}
proc.StartInfo.Password = ssPwd;
proc.Start();

并且在 IIS 中设置应用程序池身份以使用同一用户。