Solved

Open Command Prompt on remote computer and run exe returning results

Posted on 2016-09-02
4
45 Views
Last Modified: 2016-10-22
Is there a way to use .net to open a command prompt on a remote PC and run an exe?  Then I would also like to parse the response text this exe produces.  I can get this to run using psexec from my local command prompt, but I can't get it to run using .net.
0
Comment
Question by:BMFC
  • 2
4 Comments
 
LVL 33

Assisted Solution

by:it_saige
it_saige earned 500 total points
ID: 41782299
The common method used to accomplish this task is to use a program like psexec which allows for you to execute code on remote computers.  You will have to redirect the output in order to view results returned from the command console on the remote session.  This previous EE PAQ discusses the process - https:/Q_28575016.html

If you don't want to do this using the common method, then another method would be to build a service that lives on the remote computer.  You use a mechanism (think remoting or WCF) in order to communicate with this service.  The service then breaks out of the service session in order to start a process on the local workstation in order to collect results from the execution of a process.  The collected data is then sent back through the defined mechanism to the calling computer.

-saige-
1
 

Author Comment

by:BMFC
ID: 41788209
I'm sure i'm missing something, but this doesn't seem to do anything.    How do I view the response?

var process = new Process();

            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                Arguments = string.Format("-s -i \\\\server listuser.exe"),
                CreateNoWindow = true,
                FileName = "C:\\development\\psexec.exe",
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false
            };

            process.EnableRaisingEvents = true;
            process.ErrorDataReceived += OnDataReceived;
            process.OutputDataReceived += OnDataReceived;
            process.StartInfo = startInfo;
            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();
            process.WaitForExit();

Here is the response I'm currently getting back.  I'm getting something back, but the response in the middle is missing.  

Connecting to server...PsExec v2.2 - Execute processes remotelyCopyright (C) 2001-2016 Mark RussinovichStarting PSEXESVC service on server...Sysinternals - www.sysinternals.comConnecting with PsExec service on server
...Starting listuser.exe on server...listuser.exe exited on server with error code 0.

If I run this command at a command prompt, I get the full response.

c:\development> psexec \\server listuser.exe

I see it on my screen, but not in the code.  The middle is missing.
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 41788669
Try adding the '-acceptuela' argument; e.g. -
var process = new Process();

ProcessStartInfo startInfo = new ProcessStartInfo
{
	Arguments = string.Format("-acceptuela -s -i \\\\server listuser.exe"),
	CreateNoWindow = true,
	FileName = "C:\\development\\psexec.exe",
	RedirectStandardError = true,
	RedirectStandardOutput = true,
	UseShellExecute = false
};

process.EnableRaisingEvents = true;
process.ErrorDataReceived += OnDataReceived;
process.OutputDataReceived += OnDataReceived;
process.StartInfo = startInfo;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();

Open in new window


Proof of concept -
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace EE_Q28575016
{
	class Program
	{
		static void Main(string[] args)
		{
			Task task = Task.Factory.StartNew(() =>
			{
				var process = default(Process);
				var info = default(ProcessStartInfo);
				try
				{
					process = new Process() { EnableRaisingEvents = true };
					info = new ProcessStartInfo()
					{
						Arguments = @"-accepteula -s \\testserver ipconfig",
						CreateNoWindow = true,
						FileName = @"c:\_admin\pstools\psexec.exe",
						RedirectStandardError = true,
						RedirectStandardOutput = true,
						UseShellExecute = false
					};
					process.ErrorDataReceived += OnDataReceived;
					process.OutputDataReceived += OnDataReceived;
					process.StartInfo = info;

					process.Start();
					process.BeginErrorReadLine();
					process.BeginOutputReadLine();
					process.WaitForExit();
				}
				catch (Exception ex)
				{
					Console.WriteLine("Exception reported: {0} [{1}]", ex, ex.Message);
				}
				finally
				{
					if (process != null)
						process.Dispose();
				}
			});
			task.Wait();
			Console.WriteLine("Completed PSExec run on testserver");
			Console.ReadLine();
		}

		private static void OnDataReceived(object sender, DataReceivedEventArgs e)
		{
			if (e.Data != null)
				Console.WriteLine(e.Data);
		}
	}
}

Open in new window


Produces the following output -Capture.JPG
If that does not bear any fruit, try adding the runas verb to the ProcessStartInfo object; e.g. -
info = new ProcessStartInfo()
{
	Arguments = @"-accepteula -s \\testserver ipconfig",
	CreateNoWindow = true,
	FileName = @"c:\_admin\pstools\psexec.exe",
	RedirectStandardError = true,
	RedirectStandardOutput = true,
	UseShellExecute = false,
	Verb = "runas"
};

Open in new window


-saige-
0

Featured Post

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

838 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question