Solved

Open Command Prompt on remote computer and run exe returning results

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

815 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

9 Experts available now in Live!

Get 1:1 Help Now