Solved

Open Command Prompt on remote computer and run exe returning results

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

688 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