Solved

Open Command Prompt on remote computer and run exe returning results

Posted on 2016-09-02
4
56 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 34

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 34

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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

734 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