Tuesday, October 14, 2008

Remote Program Execution (using C# - WMI)

There are different methods for remote application execution. Using a client/server mechanism which sends commands to each other is a simple approach. Another one is by using .NET Remoting. One another method is by using the psexec utility, written by the great Dr. Mark Russinovich. (Personal comment: I admire his works and I believe that he is the ideal role model for all Windows programmers).

We will talk about yet another method here - using WMI. The Win32_Process class (WMI) can be used for executing processes in a remote machine. Code snippet is given below:

using System.Management;

private void RemoteExecute(string userName,
                                string password,
                                string path,
                                object[] commandLine)
{
    ConnectionOptions options = new ConnectionOptions();

    options.Impersonation = ImpersonationLevel.Impersonate;
    options.Authentication = AuthenticationLevel.Default;
    options.Username = userName;
    options.Password = password;
    options.Authority = null;
    options.EnablePrivileges = true;

    // Note: The ConnectionOptions object is not necessary
    // if we are connecting to local machine & the account has privileges
    ManagementScope scope = new ManagementScope(path, options);
    scope.Connect();

    // Create the process
    using (ManagementClass process = new ManagementClass("Win32_Process"))
    {
        process.Scope = scope;
        process.InvokeMethod("Create", commandLine);
    }
}

This code can be invoked as shown below:

object[] commandLine = { "cmd.exe", null, null, 0 };
RemoteExecute("username",
            "password",
            @"\\192.168.100.12\root\cimv2",
            commandLine);

Couple of important points to be noted: First, the launched application will not show any interface. It will be in hidden state. Also, it will not be possible to make it interactive.

Finally, WMI applications will not work if the remote machine is not configured properly. Check the below link for information about adding remote administration exception in Windows Firewall and other troubleshooting tips.

http://techblog-giri-csharp.blogspot.com/2008/10/using-wmi-with-c.html

1 comment:

Brad said...

How do you get a return value or result to know that it worked?