Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Create a Remote Process using WMI in C#

Rate me:
Please Sign up or sign in to vote.
4.81/5 (14 votes)
21 Nov 2008CPOL3 min read 184.9K   7.8K   55   8
Create a remote process using WMI in C#

Introduction

This is a simple introduction for those who are looking at WMI as an option for remotely executing the process. I believe this is in no way the first of its kind article on The Code Project and I know there may be dozens of better articles. Leaving all these apart, I still believe this may help somebody new to the .NET world looking for a simple solution to execute the process remotely. Let’s get started.

Background

This is not something I have conceptualized on my own and came up with this article here. Actually I had a problem of my own where I was trying to use WMI for remotely executing the process and had hard times. After some trial and error and lots of Googling, I came up with this prototype for using WMI to execute remote process. And this prototype was lying on my hard disk for a while now. Suddenly I found some time today to share this with The Code Project community.

Using the Code

If you have already downloaded the sample code, you must have noticed that this is a trivial command line application. The only trick worth mentioning here is the usage of a batch file. So what I am doing here is, get the remote server name, then create a batch file like below:

sBatFile = @"\\" + remoteMachine + "file://admin$//process.bat">\\admin$\\process.bat; 

So if we create the file using this variable (while you have admin access on the server), the file will be created on the remote server's Windows directory.

Next, the program receives the remote command to execute and write into this file.

Here comes the interesting part. Once we have our command residing on the remote server in the form of a BAT file, using the WMI the batch file is executed as a new process on that server. This solves the purpose of executing the code in the remote server.

C#
//
// Any source code blocks look like this
//
if (remoteMachine != string.Empty) 
 sBatFile = @"\\" + remoteMachine + "\\admin$\\process.bat"; 
else 
 Console.WriteLine("Invalid Machine name");  

if (File.Exists(sBatFile)) 
 File.Delete(sBatFile); 
StreamWriter sw = new StreamWriter(sBatFile); 
string _cmd = "DIR > <a>\\\\</a>" + remoteMachine + "\\admin$\\output.txt"; 
Console.Write("Enter the remote Command 
	<eg : Notepad.exe, Dir, Shutdown - r, etc..> : ");
_cmd = Console.ReadLine();
if ( _cmd.Trim()==string.Empty ) 
 Console.WriteLine("No command entered using default command for test :" + _cmd);  

sw.WriteLine(_cmd);
sw.Close(); 

//
//WMI section
//    
ManagemenConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
tScope manScope = new ManagementScope
	(String.Format(@"\\{0}\ROOT\CIMV2", remoteMachine), connOptions);
manScope.Connect();
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass
	(manScope, managementPath, objectGetOptions);
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["CommandLine"] = sBatFile; 
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
Console.WriteLine("Creation of the process returned: " + outParams["returnValue"]);
Console.WriteLine("Process ID: " + outParams["processId"]); 

The interesting part is the WMI section.

  1. Created the ConnectionOptions object and set the Impersonation as Impersonate. This will make sure the current users credentials are used to execute the process in the remote machine.
  2. Created the ManagementScope object by passing the root and the ConnectionOptions object. Connect() actually establishes the connection to the remote machine.
  3. Created the ProcessClass object of the type ManagementClass by passing the ManagementScope, ManagementPath objects.
  4. Called the InvokeMethod on the processClass object. This actually creates the new process on the remote server, by taking the batfile name as parameter to start a new Win32 process.

Looks like I have already written enough to publish this article.:-). Honestly this is not even 10 percent of what I wanted to tell about the WMI. Hopefully I will try to come up with a somewhat better article on WMI to provide a clear picture about the WMI object model in C#. Hoping to do that soon.

Points of Interest

Once I successfully executed my first WMI program, I was able to understand the raw power of WMI. Hope this will generate some interest on WMI for you too.

History

  • 21st November, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot running on IIS Pin
ravimittal8417-Aug-15 0:19
ravimittal8417-Aug-15 0:19 
QuestionProcess on remote server apperas in task manager but not on monitor Pin
dharmenderKumar20-Feb-14 22:10
dharmenderKumar20-Feb-14 22:10 
AnswerRe: Process on remote server apperas in task manager but not on monitor Pin
Member 1109023217-Sep-14 10:34
Member 1109023217-Sep-14 10:34 
Questionif access denied? Pin
iro4es23-Feb-10 6:11
iro4es23-Feb-10 6:11 
GeneralCapturing output of the batch file executing in the remote machine Pin
shampoo7218-May-09 19:56
shampoo7218-May-09 19:56 
Is there any way I can capture/print out the value of an error level variable (or any output -variable, echo, etc. for that matter)set by the batch file running in the remote machine through WMI.
GeneralSetting the starting folder Pin
Member 577855813-Dec-08 22:14
Member 577855813-Dec-08 22:14 
GeneralAlternate tool Pin
Ashutosh Phoujdar25-Nov-08 0:02
Ashutosh Phoujdar25-Nov-08 0:02 
GeneralAnother Pin
thund3rstruck21-Nov-08 15:34
thund3rstruck21-Nov-08 15:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.