Solved

Open Command Prompt on remote computer and run exe returning results

Posted on 2016-09-02
4
36 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 32

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 32

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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

758 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now