リモート ワークステーションでこれを実現するために、C# でいくつかのことを試してきました。
net localgroup administrators "MyAdminGroup1" /add
net localgroup administrators "MyAdminGroup2" /add
net localgroup users "MyUserGroup" /add
net localgroup users "Domain Users" /delete
cmd.exe をリモートで実行し、StreamWriter を使用してコマンドをループで実行するために PsExec を検討しました。エラーは発生していませんが、関数はハングし続けます。オンラインでいくつかのリソースを調べたところ、非同期の読み取り/書き込み、バッファーがいっぱい、PsExec が cmd.exe を無期限に待機しているなどの問題が発生していることがわかりました。
私の質問は、これについて正しい方法で進んでいますか? Process() + PsExec + cmd.exe を使用して、リモート ワークステーションで "net localgroup administrators "MyAdminGroup1" /add" を実行するか、これを達成するためのより良い方法はありますか?
StandardOutput.ReadLine() でハングするループは次のとおりです。
foreach (KeyValuePair<string, string> group in listOfLocalUserGroups) {
string label = group.Key;
string command = group.Value;
string psExecArguments = string.Format(@"-u {0}\{1} -p {2} \\{3} cmd.exe", domain, username, password, hostname);
Console.WriteLine("{0} - {1}\n{2}\nPlease wait...", label, command, psExecArguments);
Process remoteProcess = new Process();
remoteProcess.StartInfo.UseShellExecute = false;
remoteProcess.StartInfo.RedirectStandardInput = true;
remoteProcess.StartInfo.RedirectStandardOutput = true;
remoteProcess.StartInfo.RedirectStandardError = true;
remoteProcess.StartInfo.FileName = "PsExec.exe";
remoteProcess.StartInfo.Arguments = psExecArguments;
try {
List<string> strOut = new List<string>();
List<string> strErr = new List<string>();
remoteProcess.Start();
StreamWriter remoteCommand = remoteProcess.StandardInput;
remoteCommand.WriteLine(command);
remoteCommand.Close();
while (remoteProcess.StandardOutput.Peek() > -1) {
strOut.Add(remoteProcess.StandardOutput.ReadLine());
}
while (remoteProcess.StandardError.Peek() > -1) {
strErr.Add(remoteProcess.StandardError.ReadLine());
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n## {0} ##", label);
Console.WriteLine("Output: ");
foreach (string stringOut in strOut) {
Console.WriteLine(stringOut);
}
Console.WriteLine("\nError: ");
foreach (string stringErr in strErr) {
Console.WriteLine(stringErr);
}
Console.WriteLine(SuperReconfig.SECTION);
}
catch (Exception err) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Unable to complete {0}", label);
Console.WriteLine("Error: {0}\n", err.Message);
}
finally {
Console.ResetColor();
remoteProcess.Close();
}
}