远程管理本地工作站组

时间:2013-06-12 19:34:14

标签: c#

我一直在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();
            }
        }

0 个答案:

没有答案