is this the correct way to use WMI? - c#

I am trying to build a tool on the server which will open the browser on the client. note that the server and the client are in the same domain in our company.
everything works good, but when i try this to open the browswer on the client machine
string theProcessToRun = popupURL + "?CallerID=" + callerID;
string remoteIdentifier = string.Format(#"\\{0}\root\cimv2:Win32_Process", ipAddress);
ManagementClass mc = new ManagementClass(remoteIdentifier);
mc.InvokeMethod("Create", new[] { theProcessToRun });
as you see, i am using #"\\{0}\root\cimv2:Win32_Process", ipAddress, which ** I don't** know if it is the correct way because i am using windows client so i don't know what is this root has to do here
i am having this exception
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
on this line
mc.InvokeMethod("Create", new[] { theProcessToRun });
may you help please

Related

Cannot connet to sftp server from windows service

I'm working on windows service that uploads files to sftp server using SSH.NET. Problem is when I run code responsible for sending file from windows console app everything works fine, but when exact the same code is running from windows service i recive exception when connecting to SFTP : "A connection can not be made because the target computer actively refuses it"
I have SFTP server running on the same machine for testing.
public void Send(string host, string userName, int port, string password, string filePath)
{
var connectionInfo = new ConnectionInfo(host, userName, new PasswordAuthenticationMethod(userName, password));
try
{
var sftpClient = new SftpClient(connectionInfo);
sftpClient.Connect(); // exception occurs there
using (FileStream fileStream = File.OpenRead(filePath))
{
sftpClient.UploadFile(fileStream, $"{Path.GetFileName(filePath)}", true);
}
sftpClient.Disconnect();
sftpClient.Dispose();
}
catch (Exception exception)
{
Logger.Log($"{host} | {password} | {port} | {userName}");
Logger.Log(exception.Message);
Logger.Log(exception.StackTrace);
}
}
Does anyone have an idea what is going on? I think that can be some configuration problem because like I said the same code runs fine from console app.

Start process with WMI on remote machine from a share on another remote machine

I have the following code to run a process on a remote machine from a share on a second remote machine as described in the image:
(source: microsoft.com)
public class Runner
{
public static string RunExecutable(string machine, string executable, string username, string password, string domain)
{
try
{
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Authority = "kerberos:" + domain + #"\" + machine;
connectionOptions.Username = username;
connectionOptions.Password = password;
connectionOptions.Impersonation = ImpersonationLevel.Delegate;
connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy;
//define the WMI root name space
ManagementScope scope = new ManagementScope(#"\\" + machine + "." + domain + #"\root\CIMV2", connectionOptions);
//define path for the WMI class
ManagementPath p = new ManagementPath("Win32_Process");
//define new instance
ManagementClass classInstance = new ManagementClass(scope, p, null);
ManagementClass startupSettings = new ManagementClass("Win32_ProcessStartup");
startupSettings.Scope = scope;
startupSettings["CreateFlags"] = 16777216;
// Obtain in-parameters for the method
ManagementBaseObject inParams = classInstance.GetMethodParameters("Create");
// Add the input parameters.
inParams["CommandLine"] = executable;
inParams["ProcessStartupInformation"] = startupSettings;
// Execute the method and obtain the return values.
ManagementBaseObject outParams = classInstance.InvokeMethod("Create", inParams, null);
// List outParams
string retVal = outParams["ReturnValue"].ToString();
return "ReturnValue: " + retVal;
}
catch (ManagementException me)
{
return me.Message;
}
catch (COMException ioe)
{
return ioe.Message;
}
}
}
I have 5 machines in my environment, all in the same domain. 3 are running Windows Server 2008R2, one Windows 7 and one Windows XP:
WinXP
Win7
Master2008
Slave2008-1
Slave2008-2
I run the code from Master2008, the domain controller, and try to start a process on the other machines, but run into some problems when starting a process on the XP and 7 machines.
When starting the process on the WinXP and Win7 machines i get a return value of 8, which is "Unknown error", but when starting the process on the Server 2008R2 machines it works without problems.
All the machines has been marked as trusted for delegation in AD.
The process I'm trying to start is \\"machine"\c$\Windows\System32\Calc.exe
I've tried running the process from different machines, and the result was the following (The program is beeing run on Master2008):
On WinXP
- From Win7: Failed (8)
- From Slave2008-1: Failed (8)
- From Slave2008-2: Failed (8)
- From Master2008: Failed (8)
On Win7
- From WinXP: Success (0)
- From Slave2008-1: Failed (8)
- From Slave2008-2: Failed (8)
- From Master2008: Failed (8)
On Slave2008-1
- From WinXP: Success (0)
- From Win7: Success (0)
- From Slave2008-2: Success (0)
- From Master2008: Success (0)
On Slave2008-2
- From WinXP: Success (0)
- From Win7: Success (0)
- From Slave2008-1: Success (0)
- From Master2008: Success (0)
For some reason, they all fail for WinXP machine, but the Win7 machine can install from the WinXP machine.
Does anyone have any idea what can be wrong?
It seems there were no problem with the code. I tried to make a simple application to start instead of "calc.exe" and it worked as it should.
The problem was that I was trying to start "calc.exe" from 64bit servers on a 32bit clients. Also, "calc.exe" on Windows7 wont run on WindowsXP.
Don't work.
http://technet.microsoft.com/en-us/library/ee156574.aspx
You cannot use the Delegate impersonation level unless all the user accounts and computer accounts involved in the transaction have all been marked as Trusted for delegation in Active Directory. This helps minimize the security risks. Although a remote computer can use your credentials, it can do so only if both it and any other computers involved in the transaction are trusted for delegation.

C# IIS 7.5 class not registered exception

We just started up a new webserver and i'm running into "class not registered" when creating a new application pool. I'm using the code below but I have no idea how to distinguish what is not registered. Any thoughts would be awesome.
Thanks.
string path = "IIS://" + server + "/W3SVC";
string app_pools_path = path + "/AppPools";
/error below.
var app_pools = new DirectoryEntry(app_pools_path);
foreach (DirectoryEntry app_pool in app_pools.Children)
{
//do work
}
Error "Class no registered" error code:2147221164
ON the server open the server manager
add new features ==> Web Server (IIS) ==> Management Tools ==> IIS 6 Management Compatibility then check IIS6 Metabase Compatibility. use your original connection string / path
string path = "IIS://" + server + "/W3SVC";
string app_pools_path = path + "/AppPools";
try this please :
private void StopAppPool(string app_Pool , string server)
{
try
{
ConnectionOptions co = new ConnectionOptions();
co.Username = "DomainName\\UserName";
co.Password = "UserPassword";
string appPool = "W3SVC/AppPools/" + app_Pool;
co.Impersonation = ImpersonationLevel.Impersonate;
co.Authentication = AuthenticationLevel.PacketPrivacy;
string objPath = "IISApplicationPool.Name='" + appPool + "'";
ManagementScope scope = new ManagementScope(#"\\" + server + #"\root\MicrosoftIISv2", co);
using (ManagementObject mc = new ManagementObject(objPath))
{
mc.Scope = scope;
mc.InvokeMethod("Stop", null, null);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.InnerException);
Console.WriteLine(e.Data);
}
//Console.ReadLine();
}
You should avoid using DirectoryEntry to manipulate IIS 7 and above. That's the old API based on IIS ADSI interfaces,
http://msdn.microsoft.com/en-us/library/ms524896(v=vs.90).aspx
IIS 6 Compatibilities might help you out though,
http://blogs.msdn.com/b/narahari/archive/2009/05/13/when-using-directoryservices-to-access-iis-schema-iis6-management-compatibility-pack-needs-to-be-installed-system-runtime-interopservices-comexception-0x80005000.aspx
The best solution (which is also strong typed and more convenient for C# developers) is Microsoft.Web.Administration,
http://www.iis.net/learn/manage/scripting/how-to-use-microsoftwebadministration

WMI Access Denied Problem on 2003 Server

I´m having a problem whenever i try to use WMI services on a virtual pc running a 2003 Server.
The error message that i get is 'Access Denied'. I have already checked the permissions of the user over the COM components. The curious thing is that i´m running both WMI service and my app as Administrator user, so i don´t think i have trouble with permissions.
Can Anyone help me??
Thanks you very much.
The problem is on this block:
ManagementEventWatcher watcher;
try
{
numeros = devolverRandomicos();
string nros = "";
foreach (int num in numeros)
{
nros = nros + " " + num.ToString();
}
MessageBox.Show(nros);
watcher = new ManagementEventWatcher("root\\OnGuard", dataQry);
watcher.EventArrived += WMIEventArrieved;
watcher.Start();
}
catch (Exception e)
{
MessageBox.Show("ERROR CREANDO EL WATCHER: \n" + e.Message,"CatchToyota",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
The problem at last was in the Domain Users I was using to log in. After getting the machine out of the domain, all started to work just fine.
I guess it was a problem with permissions on domain users.

Creating share programmatically fails with error 9

ObjectGetOptions options = new ObjectGetOptions();
ManagementPath p = new ManagementPath("\\\\server01\\root" + "\\cimv2:Win32_Share");
// Make a connection to a remote computer.
ManagementScope scope = new ManagementScope("\\\\server01\\root\\cimv2");
scope.Connect();
// Create a ManagementClass object
ManagementClass managementClass = new ManagementClass(scope, p, options);
// Create ManagementBaseObjects for in and out parameters
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
ManagementBaseObject outParams;
// Set the input parameters
//inParams["Description"] = String.Empty;
inParams["Name"] = "test";
inParams["Path"] = #folderPath;
inParams["Type"] = 0x0; // Disk Drive
// Invoke the method on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " + outParams.Properties["ReturnValue"].Value);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
I am using the following code to set up a share, but I am always getting a return value of 9 which means invalid name. I am passing a string and have tried to use an explicit string and I still get error 9.
I am creating the share remotely rather than on local machine however. I have tried to make sure I am connecting to the remote WMI provider, but I am not sure if I have been successful.
Any suggestions from WMI gurus and others is greatly appreciated.
Found the answer on another site. The folder path needs to be the local path to the machine the share is created on, not a UNC path like I was using.
I had the same error. In my case though the problem was a trailing backslash. Doing directoryPath.TrimEnd('\') solved the problem.
Return Values
Returns one of the values in the following table or any other value to indicate an error.
0 – Success
2 – Access denied
8 – Unknown failure
9 – Invalid name
10 – Invalid level
21 – Invalid parameter
22 – Duplicate share
23 – Redirected path
24 – Unknown device or directory
25 – Net name not found

Categories

Resources