Home » Windows » Run a command in a windows remote server and get back the console output in C# .NET

Run a command in a windows remote server and get back the console output in C# .NET

Posted by: admin February 27, 2018 Leave a comment

Questions:

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

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

Is there a way to do it in C#?

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);

Any Ideas?

Answers:

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;
    }
}

Questions:
Answers:

You can try executing a command with PsTools. One of many features they offer is PsExec. It allows you to run a command on a remote server. It should also return the results into a console (on local PC where it was run from).