Tag Archives: Remote Machine

Method to run process on remote machine using WMI/PSEXEC and C#

The method below can run the process on a remote machine using WMI
*Note: It does not initiates the process visibly on the desktop screen whereas starts as a hidden process. So can be used only when you need to start the process in hidden mode.

We will need to add reference to “System.Management” and add below two namespaces to the library
using System.IO;
using System.Management;


private static void runProcessOnRemoteMachine(string remoteMachine, string strPathToTheExe, string Parameter,string usernameAndDomain, string password)
{
try
{
if (File.Exists(strPathToTheExe))
{
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
if (Environment.MachineName.ToUpper() != remoteMachine.ToUpper())
{
connOptions.Username = usernameAndDomain; //It should be like domain\username
connOptions.Password = password;
}
ManagementScope 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"] = strPathToTheExe + " \"" + Parameter + "\"";
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
Console.WriteLine("Creation of the process returned: " + outParams["returnValue"]);
Console.WriteLine("Process ID: " + outParams["processId"]);
}

else
{
Console.WriteLine("Could not find the executable");
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occured in method runProcessOnRemoteMachine : " + ex.Message.ToString());
}
}

For more information on InvokeMethod : http://msdn.microsoft.com/en-us/library/f9ck6sf2(v=vs.110).aspx

If you want to start a process visible on the desktop screen, then can make use of PSEXEC in order to start process on the remote machine.
for the method below you will need to add below two namespaces
using System.Diagnostics;
using System.Threading;


private static void InitiateProcessOnRemoteMachine(string _remoteMachineName, string executableFileCompletePath, string ParamForExeFile)
{

string psexec = @"c:\psexec\psexec.exe"; //Path to psexec
//If we need to pass some parameter then we need to pass it with the exe enclose in double coutes else can just use path to executable
string command = executableFileCompletePath + " \"" + ParamForExeFile + "\"";
string node = @"\\" + _remoteMachineName;
string arguments = "-i " + node + " -u " + "UserName" + " -p " + "password" + " " + command; //parameters
Console.WriteLine(arguments); //The arguments ready for psexec

Process Psexec = new Process();
Psexec.StartInfo.FileName = psexec;
Psexec.StartInfo.Arguments = "-accepteula";
Psexec.Start();
System.Threading.Thread.Sleep(3000);

Process GenTCM = new Process();
GenTCM.StartInfo.FileName = psexec;
GenTCM.StartInfo.Arguments = arguments;
GenTCM.StartInfo.UseShellExecute = false;
GenTCM.StartInfo.RedirectStandardError = true;
GenTCM.Start();
int intTimeOut = 100;
int Flag = 0;
while (GenTCM.HasExited == false)
{
Thread.Sleep(1000);
Flag = Flag + 1;
if (intTimeOut == Flag )
{
Process[] psexecProcess = Process.GetProcessesByName("psexec");
foreach (Process p in psexecProcess)
{ p.Kill(); }
break;
}
}
string actualOutput = "";
string errorOutput = GenTCM.StandardError.ReadToEnd();
if (errorOutput.Contains("error code") && !errorOutput.Contains("error code 0"))
{
string[] output = errorOutput.Split(new[] { '\n' });
errorOutput = output[5];
Console.WriteLine("[ERROR] " + errorOutput + "\r\n");
}
else
{
string[] output = errorOutput.Split(new[] { '\n' });
actualOutput = output[5];
actualOutput = actualOutput.Replace("\r", "");
Console.WriteLine("[SUCCESS] TCM Command is launched.\r\n" + actualOutput);
}

}

For more information on psexec: http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx

Get a Loaded DLL for a process on Remote machine

The method below with get you the loaded dll for a process running on a remote machine.
The language used in C# and powershell cmdlet is used to get the information

you will need these two namespaces to be used for the same.
using System.Management.Automation;
using System.Management.Automation.Runspaces;

public bool getDLLLoadedOnRemoteMachine(string processName, string dLLToCheck, string MachineName, string strDomainAdminUser, string domainUserPassword)
{

var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
var pipe = runspace.CreatePipeline();
pipe.Commands.AddScript("$PSComputer = '" + MachineName + "'");
pipe.Commands.AddScript("$username = \"" + strDomainAdminUser + "\"");
pipe.Commands.AddScript("$password = convertto-securestring \"" + domainUserPassword + "\" -asplaintext -force");
pipe.Commands.AddScript("$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password");
pipe.Commands.AddScript("$Session = New-PSSession -ComputerName $PSComputer -Credential $cred -ConfigurationName \"microsoft.powershell32\"");
pipe.Commands.AddScript("$AllModules = Invoke-Command -Session $Session -ScriptBlock{(Get-Process " + processName + ").Modules }");
pipe.Commands.AddScript("Remove-PSSession $Session");
pipe.Commands.AddScript("$AllModules");

try
{
foreach (PSObject result in pipe.Invoke())
{
var str = result.ToString();
if (str.ToUpper().IndexOf(dLLToCheck.ToUpper()) != -1)
{
return true;
}
}
return false;
}
catch (Exception e)
{
if (e.InnerException != null)
{
Console.WriteLine("Invoke Exception: " + e.InnerException.ToString());
return false;
}
else
{
Console.WriteLine("Invoke Exception: " + e.Message.ToString());
return false;
}
}
}

You will need to add a reference to your project.

System.Management.automation

For Win7/2008r2 you need to install Windows Management Framework 3.0 Please find the link to the download provided below.
http://www.microsoft.com/en-us/download/details.aspx?id=34595