Click here to Skip to main content
Click here to Skip to main content

Create a Remote Process using WMI in C#

By , 21 Nov 2008
 

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.

//
// 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)

About the Author

Moorthi N
Software Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionif access denied?memberiro4es23 Feb '10 - 6:11 
GeneralCapturing output of the batch file executing in the remote machinemembershampoo7218 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 foldermemberMember 577855813 Dec '08 - 22:14 
GeneralAlternate toolmemberashu fouzdar25 Nov '08 - 0:02 
GeneralAnothermemberthund3rstruck21 Nov '08 - 15:34 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 21 Nov 2008
Article Copyright 2008 by Moorthi N
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid