1

我一直在 C# 中尝试一些东西来在远程工作站上完成此任务:

net localgroup administrators "MyAdminGroup1" /add
net localgroup administrators "MyAdminGroup2" /add
net localgroup users "MyUserGroup" /add
net localgroup users "Domain Users" /delete

考虑 PsExec 远程执行 cmd.exe 并使用 StreamWriter 循环运行命令。我没有收到错误,但该功能一直挂起。我在网上筛选了一些资源,了解到我遇到了异步读/写、缓冲区已满、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();
            }
        }
4

0 回答 0