Lauch a process on a remote machine with impersonation c# - c#

I'm trying to launch a process using impersonation with WMI and C#.
Here's what I have so far:
var coptions = new ConnectionOptions();
coptions.Username = String.Format(#"{0}\{1}", machine.Domain, machine.Username);
coptions.Password = machine.Password;
coptions.Impersonation = ImpersonationLevel.Impersonate;
coptions.EnablePrivileges = true;
var mScope = new ManagementScope(String.Format(#"\\{0}\root\cimv2", machine.Address), coptions);
var mClass = new ManagementClass(mScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
object[] generatorProcess = { #"C:\test\test1.exe" };
mClass.InvokeMethod("Create", generatorProcess);
Exception:
E_ACCESSDENIED at mClass.InvokeMethod
How can I do it?
PS: The user I'm launching the process with does not have admin privileges, is it required?
EDIT: It works with an admin, looks like it's the user..
I've followed this guide here to try and give permissions without sucess.
https://support.infosim.net/demo/wmi/wmi.html
Help please

Basically, you can't do it with an account that has limited permissions. You can tweak the permissions on the WMI object to read but not to write it does not work at all.

Related

WMI remote process fails to start, starts locally fine

The following code works when "SelectedMachine" is the localhost where the C# exe is being launched from. When "SelectedMachine" is a remote machine, the process simply doesn't launch. No exceptions, no errors, acts as if it's successful, however, the process never starts. Any ideas?
object[] processToRun = { "notepad.exe" };
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.Authentication = AuthenticationLevel.PacketPrivacy;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(#"\\{0}\ROOT\CIMV2", SelectedMachine), connOptions);
manScope.Connect();
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
processClass.InvokeMethod("Create", processToRun );
Edit: When I go through wbemtest, same behavior occurs. When the Namespace is root\cimv2 (local), the process executes, when it is \RemoteMachineName\root\cimv2, it claims success but never starts on the remote machine. Not sure what I'm missing here.
This behavior is described in the Win32_Process.Create method documentation.
For security reasons the Win32_Process.Create method cannot be used to
start an interactive process remotely.

WMI: “File not found” when trying to retrieve “ServerNetworkProtocol” scope for SQL Server

I am trying to get Server Network Protocol (SQL Server) using WMI.
I had written small application:
---------------------------C# code--------------------------
ManagementScope scope = new ManagementScope(#"\\computerName\root\Microsoft\SqlServer\ComputerManagement");
scope.Options.Username = "Administrator";
scope.Options.Password = "Password";
scope.Connect();
var query = new ObjectQuery(#"SELECT * FROM ServerNetworkProtocol");
var searcher = new ManagementObjectSearcher(scope, query);
var managementObjectCollection = searcher.Get();
var result = managementObjectCollection.Cast<ManagementObject>().ToList(); //<---- FileNotFoundException
var s = result.First()["ProtocolName"].ToString();
MessageBox.Show(String.Format("Protocol name: {0}", s));
And when I run the application, I will receive System.IO.FileNotFoundException.
I tested the query using WBEMTest Utility and everything is okey (with Administrator credentials).
Later I had written test service and put the same code, and service works correctly without any exceptions.
I suppose the problem related with credentials.
Can anyone explain more detailed what's wrong. What permissions need to run this query (if problem with credentials) and how I can resolve the issue.
I will be appreciated for any help.
just check credential and change one line :
ManagementScope scope = new ManagementScope(#"\\computerName\root\Microsoft\SqlServer\ComputerManagement10");

Specify that a remote process created by wmi should interact with the desktop

I know I can create a remote process via WMI, something like:
object[] theProcessToRun = { "notepad.exe" };
var path = new ManagementPath(String.Format(#"\\{0}\root\cimv2", "win7test-hyperv"));
var scope = new ManagementScope(path);
var theClass = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
theClass.InvokeMethod("Create", theProcessToRun);
But can I specify that should interact with the desktop (like psexec's -i)? I'd also like to be able to specify what user session the UI should interact with?
For security reasons the Win32_Process.Create method cannot be used to start an interactive process remotely.

Trying to run psexec to remote to server and recycle app pool

If I run this from my command prompt it works fine.
psexec \ServerName cscript.exe iisapp.vbs /a AppName /r
I'm trying to do the same thing with C# console app. I'm using the below code but most of the time the application hangs and doesn't complete, and the few times it does it throws an error code. Am I doing this wrong? Does anyone know where I can look up the error or error code?
static void RecycleAppPool(string sServer)
{
Console.Clear();
ProcessStartInfo p = new ProcessStartInfo("psexec.exe", "\\\\" + sServer + " cscript.exe iisapp.vbs /a <AppName> /r");
p.RedirectStandardInput = true;
p.UseShellExecute = false;
Process.Start(p);
}
When it completes with an error, looks like this
"cscript.exe exited with error code -2147024664"
EDIT
Below code working well
static void RecycleAppPool(string sServer)
{
Console.Clear();
ProcessStartInfo p = new ProcessStartInfo("psexec.exe");
p.Arguments = #"\\" + sServer + #" cscript.exe iisapp.vbs /a AppName /r";
p.UseShellExecute = false;
Process.Start(p);
}
VS2003/8/10: Tools->Error Lookup. Paste in the error code in hex. 800700E8. It's "The pipe is being closed." Not very helpful - some issue with redirection i guess.
Do you really have in the ProcessStartInfo parameter, or is that being used to replace what your actual app name is?
Have you tried recycling using appcmd instead of iisapp.vbs?
And, in this thread they recycled a remote application pool using WMI.
If it's IIS7 then you can you the web admin namespace from C#:
using System;
using System.Xml.Serialization;
using Microsoft.Web.Administration;
using System.Linq;
using System.Runtime.InteropServices;
///...
var serverManager = ServerManager.OpenRemote(#"\\myiisserver");
var appPool = serverManager.ApplicationPools["my app pool name"];
appPool.Recycle();
You can learn more about the Web Admin Namespace here. So far it has worked very well for us. BUT must be installed on the client and remote machines.
I struggled with this a lot for the last 2 days trying every solution I found online. I'm trying to recycle an application pool on remote machines on a different domain. The first method I tried with PsExec returned error 3. I tried DirectoryEntry and failed on permissions as well and then tried using ServerManager but the same issue.
Finally, I moved to WMI and it worked:
public static void RecycleIis4(string user, string password, string serverName = "LOCALHOST", string appPoolName = "DefaultAppPool")
{
var processToRun = new[] { #"c:\Windows\system32\inetsrv\appcmd recycle APPPOOL " + appPoolName };
var connection = new ConnectionOptions { Username = user, Password = password };
var wmiScope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", serverName), connection);
var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
wmiProcess.InvokeMethod("Create", processToRun);
}
Hope this helps.

WMI + Bitlocker + C# Get encrypted Volumes produces timeout

i want to create a wrapper class for specific WMI functions that affect Bitlocker functionality. The first step is to get all the Bitlocker volumes of a machine so I created a Console Application and did this:
private static ManagementClass management;
private static ManagementObjectCollection Volumes = null;
static void Main(string[] args)
{
ManagementPath path = new ManagementPath();
path.Server = "";
path.NamespacePath = "\\ROOT\\CIMV2\\Security\\MicrosoftVolumeEncryption";
path.ClassName = "Win32_EncryptableVolume";
ConnectionOptions options = new ConnectionOptions();
options.Authentication = AuthenticationLevel.PacketPrivacy;
options.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(path, options);
ObjectGetOptions getOptions = new ObjectGetOptions();
management = new ManagementClass(scope, path, getOptions);
management.Get();
Volumes = management.GetInstances();
}
When I run this on a non-Bitlocker machine the Volumes Collection gets initialized OK, only that it has a Count of 0 of course. Now I copied the code over to a WinForms App and when I click a button to run this code it steps through OK but when I try to expand the collection during debugging the App hangs and I get a "Function evaluation timed out". It's the same code just in another Application. What could be the reason for this?
Hm. I got a null reference exception if I didn't run it as administrator, but when I ran it as administrator (Win 7 x64, btw), I got four Volumes back.
I just had a similar issue, I will post my code for you hopefully it helps.
ManagementObjectSearcher Encryption = new ManagementObjectSearcher(#"root\cimv2\Security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume");
foreach (ManagementObject QueryObj in Encryption.Get())
{
string EncryptionStatus = QueryObj.GetPropertyValue("ProtectionStatus").ToString();
if (EncryptionStatus == "0")
{
EncryptionDialog.Text = "Unencrypted";
}
else if (EncryptionStatus == "1")
{
EncryptionDialog.Text = "Encrypted - SysPrep will not complete";
}
else if (EncryptionStatus == "2")
{
EncryptionDialog.Text = "Cannot Determine Encryption";
}
}
I'm using this to display the status for a sysprep tool i'm creating so the "EncryptionDialog.Text = ..." can be replaced with any other calls you may need. you also need to remember "which caused me issues at least" if you are using visual studio you will need to add a file to your project labeled "Application Manifest File" in the "Add New File" Dialog. The reason for this is that the application will need to be opened in Administrator mode(Just an FYI in case you haven't made it that far)

Categories

Resources