how to access romote windows service with Related ObjectQuery - c#

I want to control (start and stop) a windows service which is in the remote machine. I can connect that machine but I can't access to windows service. Here is my code.
Can you help me?
ConnectionOptions oConn = new ConnectionOptions();
oConn.Username = "****";
oConn.Password = "****";
ManagementScope managementScope = new ManagementScope(#"\\***.***.***.***\root\CIMV2", oConn);
managementScope.Connect();
RelatedObjectQuery roq = new RelatedObjectQuery("Win32_Service.Name='KanAktarim'");
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(managementScope, roq);
ManagementObjectCollection mbCollection = moSearcher.Get();

ManagementObjectSearcher moSearcher = new ManagementObjectSearcher();
moSearcher.Scope = managementScope;
moSearcher.Query = new ObjectQuery("SELECT * FROM win32_Service WHERE Name ='KanAktarim'");
ManagementObjectCollection mbCollection = moSearcher.Get();
foreach (ManagementObject oReturn in mbCollection)
{
ManagementBaseObject outParams = oReturn.InvokeMethod("StartService", null, null);
ManagementBaseObject outParams = oReturn.InvokeMethod("StopService", null, null);
string a = outParams["ReturnValue"].ToString();
string state = oReturn.Properties["State"].Value.ToString().Trim();
}

Related

ManagementObjectCollection returns null

Hey i have some code to generate Hardware Id for identification and it have worked fine for several month but now without any changes it stopped working it stops at all of these
ManagementObjectCollection cpu_Collection = cpu.Get();
ManagementObjectCollection hdd_Collection = hdd.Get();
ManagementObjectCollection bios_Collection = bios.Get();
Can anyone help me fix it this is all of my code to get the hardware id
//public static string test = ReturnHardwareID().ToString();
private static async Task<string> ReturnHardwareID()
{
byte[] bytes;
byte[] hashedBytes;
StringBuilder sb = new StringBuilder();
Task task = Task.Run(() =>
{
ManagementObjectSearcher cpu = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
ManagementObjectCollection cpu_Collection = cpu.Get();
foreach (ManagementObject obj in cpu_Collection)
{
sb.Append(obj["ProcessorId"].ToString().Substring(0, 4));
break;
}
ManagementObjectSearcher hdd = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
ManagementObjectCollection hdd_Collection = hdd.Get();
foreach (ManagementObject obj in hdd_Collection)
{
sb.Append(obj["Model"].ToString().Substring(0, 4));
break;
}
ManagementObjectSearcher bios = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");
ManagementObjectCollection bios_Collection = bios.Get();
foreach (ManagementObject obj in bios_Collection)
{
sb.Append(obj["Version"].ToString().Substring(0, 4));
break;
}
});
Task.WaitAll(task);
bytes = Encoding.UTF8.GetBytes(sb.ToString());
hashedBytes = SHA256.Create().ComputeHash(bytes);
return await Task.FromResult(Convert.ToBase64String(hashedBytes).Substring(25));
}

Get ids on windows

I have an error that I cannot solve, not even searching the internet.
My code:
public static void GetClasses(ref List<ListViewItem> items)
{
ManagementPath path = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CIMV2", SystemInformation.ComputerName.ToUpperInvariant()));
ConnectionOptions options = new ConnectionOptions
{
EnablePrivileges = true,
Impersonation = ImpersonationLevel.Impersonate,
Authentication = AuthenticationLevel.Default,
Username = null,
SecurePassword = null
};
ManagementScope managementScope = new ManagementScope(path, options);
managementScope.Connect();
ObjectGetOptions options2 = new ObjectGetOptions();
new ManagementScope(new ManagementObject(managementScope, path, options2).Path, options);
ObjectQuery query = new ObjectQuery("SELECT * FROM meta_class WHERE __Class LIKE \"%%%\" AND NOT __Class LIKE \"[_][_]%\" AND NOT __Class LIKE \"Win32_Perf%\" AND NOT __Class LIKE \"MSFT[_]%\"");
EnumerationOptions options3 = new EnumerationOptions
{
EnumerateDeep = true,
UseAmendedQualifiers = true
};
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, query, options3);
new List<WMIClass>();
foreach (ManagementClass managementClass in from ManagementClass currentClass in managementObjectSearcher.Get()
orderby currentClass.ClassPath.ClassName
select currentClass)
{
bool flag = false;
// using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())
using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
{
while (enumerator2.MoveNext())
{
if (enumerator2.Current.Type == CimType.String)
{
flag = true;
}
}
}
if (flag)
{
WMIClass wmiclass = new WMIClass(managementClass);
ListViewItem listViewItem = new ListViewItem
{
Name = wmiclass.DisplayName,
Text = wmiclass.DisplayName,
ToolTipText = wmiclass.Description,
Tag = wmiclass
};
listViewItem.SubItems.Add(wmiclass.Description);
items.Add(listViewItem);
}
}
}
Error line:
using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
// using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())
I don't know what the mistake is. If you can help me please I don't understand the language very well.
I would greatly appreciate your help.
Try changing
using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
{
while (enumerator2.MoveNext())
{
if (enumerator2.Current.Type == CimType.String)
{
flag = true;
}
}
}
to
PropertyDataCollection.PropertyDataEnumerator enumerator2 = managementClass.Properties.GetEnumerator();
while (enumerator2.MoveNext())
{
if (enumerator2.Current.Type == CimType.String)
{
flag = true;
}
}
First, "using" must be removed because GetEnumerator() does not return a disposable object and second, use "managementClass.Properties.GetEnumerator()" instead of "ManagementClass.Properties.GetEnumerator()".

Getting "Invalid query" ManagementException

I am trying to get system information of the machine which is in domain.
Below is my code for that.
ConnectionOptions opt = new ConnectionOptions();
opt.Authentication = System.Management.AuthenticationLevel.Packet;
opt.Impersonation = ImpersonationLevel.Impersonate;
opt.EnablePrivileges = true;
opt.Username = strUserName;
opt.Password = strPassword;
ManagementPath p = new ManagementPath("\\\\" + strServerName + "\\root\\cimv2");
ManagementScope scope = new ManagementScope(p, opt);
ObjectQuery query = new ObjectQuery("SELECT Architecture FROM Win32_Processor");
ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection results = search.Get();
ManagementObjectCollection.ManagementObjectEnumerator e = results.GetEnumerator();
e.MoveNext();
ushort arch = (ushort)e.Current["Architecture"];
I am getting exception of invalid query on e.MoveNext() line.This code is running perfectly fine for almost all machine but in some machine it is giving such an exception. I don't know why this exception occur and how to solve it?

WMI to retrieve website physical path in c#

I've created this VBScript WMI script:
On Error Resume Next
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
Set objWMIService = GetObject("winmgmts:\\localhost\root\MicrosoftIISv2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM IIsWebVirtualDirSetting", _
"WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
For Each objItem In colItems
WScript.Echo "Path: " & objItem.Path
WScript.Echo
Next
Which returns the physical path (C:\inetpub\wwwroot\webapplication1) to all the applications in IIS.
Now I'm trying to use C# to populate a combobox with those values:
public static ArrayList Test2()
{
ArrayList WebSiteListArray = new ArrayList();
ConnectionOptions connection = new ConnectionOptions();
ManagementScope scope =
new ManagementScope(#"\\" + "localhost" + #"\root\MicrosoftIISV2",
connection);
scope.Connect();
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope,
new ObjectQuery("SELECT * FROM IIsWebVirtualDirSetting"), null);
ManagementObjectCollection webSites = searcher.Get();
foreach (ManagementObject webSite in webSites)
{
WebSiteListArray.Add(webSite.Path);
}
return WebSiteListArray;
}
But the output is the virtual path:
(`IIsWebVirtualDirSetting.Name="W3SVC/1/ROOT/webapplication1"`)
What needs to be changed in my query?
Note: I need to support IIS6 and .NET 4.0
Finally got it...
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\MicrosoftIISv2",
"SELECT * FROM IIsWebVirtualDirSetting");
foreach (ManagementObject queryObj in searcher.Get())
{
result.Add(queryObj["Path"]);
}
I prefer like this:
Connect at my local network server SOMEREMOTESERVER:
ConnectionOptions connection = new ConnectionOptions();
connection.Authentication = System.Management.AuthenticationLevel.PacketPrivacy;
ManagementScope scope =
new ManagementScope(#"\\SOMEREMOTESERVER\root\MicrosoftIISV2",
connection);
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM IISWebServerSetting");
var collection = new ManagementObjectSearcher(scope, query).Get();
foreach (ManagementObject item in collection)
{
var value = item.Properties["ServerBindings"].Value;
if (value is Array)
{
foreach (ManagementBaseObject a in value as Array)
{
Console.WriteLine(a["Hostname"]);
}
}
ManagementObject maObjPath = new ManagementObject(item.Scope,
new ManagementPath(
string.Format("IISWebVirtualDirSetting='{0}/root'", item["Name"])),
null);
PropertyDataCollection properties = maObjPath.Properties;
Console.WriteLine(properties["path"].Value);
Console.WriteLine(item["ServerComment"]);
Console.WriteLine(item["Name"]);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
}

C# - How to get list of USERs/GROUPs having access to shared folder on a Remote Machine

I wanted to write a code in C# to list all the users/groups having access (Read/Write/Full) to a shared folder on a server.
For Example: I have a shared folder \servername\MyData. Now I wanted to list the users/groups who have access to this folder.
This should get you pointed in the right direction, I can't test it atm but should be something similar.
private bool CheckAccess(DirectoryInfo directory)
{
// Get the collection of authorization rules that apply to the current directory
AuthorizationRuleCollection acl = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
foreach (var rule in acl)
{
// do something here
}
}
private DataTable GetSharedFolderAccessRule()
{
DataTable DT = new DataTable();
try
{
DT.Columns.Add("ShareName");
DT.Columns.Add("Caption");
DT.Columns.Add("Path");
DT.Columns.Add("Domain");
DT.Columns.Add("User");
DT.Columns.Add("AccessMask");
DT.Columns.Add("AceType");
ManagementScope Scope = new ManagementScope(#"\\.\root\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_LogicalShareSecuritySetting");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
ManagementObjectCollection QueryCollection = Searcher.Get();
foreach (ManagementObject SharedFolder in QueryCollection)
{
{
String ShareName = (String) SharedFolder["Name"];
String Caption = (String)SharedFolder["Caption"];
String LocalPath = String.Empty;
ManagementObjectSearcher Win32Share = new ManagementObjectSearcher("SELECT Path FROM Win32_share WHERE Name = '" + ShareName + "'");
foreach (ManagementObject ShareData in Win32Share.Get())
{
LocalPath = (String) ShareData["Path"];
}
ManagementBaseObject Method = SharedFolder.InvokeMethod("GetSecurityDescriptor", null, new InvokeMethodOptions());
ManagementBaseObject Descriptor = (ManagementBaseObject)Method["Descriptor"];
ManagementBaseObject[] DACL = (ManagementBaseObject[])Descriptor["DACL"];
foreach (ManagementBaseObject ACE in DACL)
{
ManagementBaseObject Trustee = (ManagementBaseObject)ACE["Trustee"];
DataRow Row = DT.NewRow();
Row["ShareName"] = ShareName;
Row["Caption"] = Caption;
Row["Path"] = LocalPath;
Row["Domain"] = (String) Trustee["Domain"];
Row["User"] = (String) Trustee["Name"];
Row["AccessMask"] = (UInt32) ACE["AccessMask"];
Row["AceType"] = (UInt32)ACE["AceType"];
DT.Rows.Add(Row);
DT.AcceptChanges();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
return DT;
}

Categories