How to execute process on remote machine, in C#

夙愿已清 提交于 2019-11-26 17:45:49
Ivan G.

Can can use PsExec from http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx

Or WMI:

object theProcessToRun() = { "YourFileHere" };

ManagementClass theClass = new ManagementClass(@"\\server\root\cimv2:Win32_Process");

theClass.InvokeMethod("Create", theProcessToRun);

Use one of the following:

Or if you feel like it, inject your own service or COM component. That would be very close to what PsExec does.

Of all these methods, I prefer task scheduler. The cleanest API of them all, I think. Connect to the remote task scheduler, create a new task for the executable, run it. Note: the executable name should be local to that machine. Not \servername\path\file.exe, but c:\path\file.exe. Delete the task if you feel like it.

All those methods require that you have administrative access to the target machine.

ProcessStartInfo is not capable of launching remote processes.

According to MSDN, a Process object only allows access to remote processes not the ability to start or stop remote processes. So to answer your question with respect to using this class, you can't.

live2

An example with WMI and other credentials as the current process, on default it used the same user as the process runs.

var hostname = "server"; //hostname or a IpAddress

var connection = new ConnectionOptions();
//The '.\' is for a local user on the remote machine
//Or 'mydomain\user' for a domain user
connection.Username = @".\Administrator";
connection.Password = "passwordOfAdministrator";

object[] theProcessToRun = { "YourFileHere" }; //for example notepad.exe

var wmiScope = new ManagementScope($@"\\{hostname}\root\cimv2", connection);
wmiScope.Connect();
using (var managementClass = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()))
{
    managementClass.InvokeMethod("Create", theProcessToRun);
}

I don't believe you can start a process through a UNC path directly; that is, if System.Process uses the windows comspec to launch the application... how about you test this theory by mapping a drive to "\someComputer\somePath", then changing your creation of the ProcessStartInfo to that? If it works that way, then you may want to consider temporarily mapping a drive programmatically, launch your app, then remove the mapping (much like pushd/popd works from a command window).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!