在Windows远程服务器中运行命令,并在C#.NET中返回控制台输出 [英] Run a command in a windows remote server and get back the console output in C# .NET

查看:145
本文介绍了在Windows远程服务器中运行命令,并在C#.NET中返回控制台输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个远程服务器名称(Windows),用户名密码

I have a remote server name (windows), username and password.

使用C#.Net,我想在远程服务器上运行命令,返回 控制台输出

Using C# .Net, I want to run a command on the remote server and get back the console output

在C#中有没有办法做到这一点?

Is there a way to do it in C#?

我能够使用 WMI 和以下代码(部分)来运行命令,但是没有运气控制台输出。我只能找回进程ID

I was able to run the command using WMI with the following code (partial) but with no luck of getting the console output. I could only get back the Process ID.

ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(scope, managementPath,objectGetOptions);

ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

inParams["CommandLine"] = "cmd.exe /c "+ mycommand;
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

有什么想法吗?

推荐答案

此功能是我经过研究后想到的。希望对其他人有所帮助。

This function is what I came up with after some research. Hope it helps someone else.

public string executeCommand(string serverName, string username, string password, string domain=null, string command)
{
    try
    {
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.RedirectStandardOutput = true;
        startInfo.UseShellExecute = false;
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        if (null != username)
        {
            if (null != domain)
            {
                startInfo.Arguments = "/C \"psexec.exe \\\\" + serverName + " -u " + domain+"\\"+username + " -p " + password + " " + command + "\"";
            }
            else
            {
                startInfo.Arguments = "/C \"psexec.exe \\\\" + serverName + " -u " + username + " -p " + password + " " + command + "\"";
            }
        }
        else
        {
            startInfo.Arguments = "/C \"utils\\psexec.exe "+serverName+" "+ command + "\"";
        }
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();

        if (process.ExitCode == 0 && null != process && process.HasExited)
        {
           return process.StandardOutput.ReadToEnd();
        }
        else
        {
            return "Error running the command : "+command;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

这篇关于在Windows远程服务器中运行命令,并在C#.NET中返回控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆