private async Task PollNetworkUtilization() { const string queryTemplate = @"select BytesReceivedPersec, BytesSentPersec, PacketsReceivedPersec, PacketsSentPersec FROM Win32_PerfFormattedData_Tcpip_NetworkInterface where name = '{name}'"; foreach (var iface in Interfaces) { var perfCounterName = iface.Name; //adjust performance counter special symbols for instance name. perfCounterName = perfCounterName.Replace("\\", "_"); perfCounterName = perfCounterName.Replace("/", "_"); perfCounterName = perfCounterName.Replace("(", "["); perfCounterName = perfCounterName.Replace(")", "]"); perfCounterName = perfCounterName.Replace("#", "_"); var query = queryTemplate.Replace("{name}", perfCounterName); using (var q = Wmi.Query(Name, query)) { var data = await q.GetFirstResult(); if (data == null) { continue; } iface.InBps = data.BytesReceivedPersec; iface.OutBps = data.BytesSentPersec; iface.InPps = data.PacketsReceivedPersec; iface.OutPps = data.PacketsSentPersec; AddNetworkUtilization(iface, new Interface.InterfaceUtilization { DateTime = DateTime.UtcNow, InMaxBps = iface.InBps, OutMaxBps = iface.OutBps }); } } }
private async Task <bool> GetCanQueryAdapterUtilization() { // it's much faster trying to query something potentially non existent and catching an exception than to query the "meta_class" table. const string query = "SELECT name FROM Win32_PerfRawData_Tcpip_NetworkAdapter"; try { using (var q = Wmi.Query(Endpoint, query)) { await q.GetFirstResultAsync().ConfigureAwait(false); } } catch { return(false); } return(true); }
private async Task GetAllVolumesAsync() { const string query = @" SELECT Caption, DeviceID, Description, FreeSpace, Name, Size, VolumeSerialNumber FROM Win32_LogicalDisk WHERE DriveType = 3"; //fixed disks using (var q = Wmi.Query(Endpoint, query)) { foreach (var disk in await q.GetDynamicResultAsync().ConfigureAwait(false)) { var id = $"{disk.DeviceID}"; var v = Volumes.Find(x => x.Id == id) ?? new Volume(); v.Id = $"{disk.DeviceID}"; v.Available = disk.FreeSpace; v.Caption = disk.VolumeSerialNumber; v.Description = disk.Name + " - " + disk.Description; v.Name = disk.Name; v.NodeId = Id; v.Size = disk.Size; v.Type = "Fixed Disk"; v.Status = NodeStatus.Active; v.Used = v.Size - v.Available; if (v.Size > 0) { v.PercentUsed = 100 * v.Used / v.Size; } if (v.Node == null) { v.Node = this; Volumes.Add(v); } } } }
private async Task GetAllVolumes() { const string query = @" SELECT Caption, DeviceID, Description, FreeSpace, Name, Size, VolumeSerialNumber FROM Win32_LogicalDisk WHERE DriveType = 3"; //fixed disks using (var q = Wmi.Query(Name, query)) { foreach (var disk in await q.GetDynamicResult()) { var id = $"{disk.DeviceID}"; var v = Volumes.FirstOrDefault(x => x.Id == id); if (v == null) { v = new Volume(); Volumes.Add(v); } v.Id = $"{disk.DeviceID}"; v.Available = disk.FreeSpace; v.Caption = disk.VolumeSerialNumber; v.Description = disk.Name + " - " + disk.Description; v.Name = disk.Name; v.NodeId = Id; v.Size = disk.Size; v.Type = "Fixed Disk"; v.Status = NodeStatus.Active; v.Used = v.Size - v.Available; if (v.Size > 0) { v.PercentUsed = (float)(100 * v.Used / v.Size); } } } }
private async Task PollCpuUtilizationAsync() { var query = IsVMHost ? "SELECT Name, Timestamp_Sys100NS, PercentTotalRunTime FROM Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor WHERE Name = '_Total'" : "SELECT Name, Timestamp_Sys100NS, PercentProcessorTime FROM Win32_PerfRawData_PerfOS_Processor WHERE Name = '_Total'"; var property = IsVMHost ? "PercentTotalRunTime" : "PercentProcessorTime"; using (var q = Wmi.Query(Endpoint, query)) { var data = await q.GetFirstResultAsync().ConfigureAwait(false); if (data == null) { return; } var perfData = new PerfRawData(this, data); if (IsVMHost) { CPULoad = (short)(perfData.GetCalculatedValue(property, 100D) / NumberOfLogicalProcessors); } else { CPULoad = (short)Math.Round((1 - perfData.GetCalculatedValue(property)) * 100); } var cpuUtilization = new CPUUtilization { DateEpoch = DateTime.UtcNow.ToEpochTime(), AvgLoad = CPULoad }; UpdateHistoryStorage(CPUHistory, cpuUtilization); } }
private async Task PollMemoryUtilizationAsync() { const string query = "SELECT AvailableKBytes FROM Win32_PerfRawData_PerfOS_Memory"; using (var q = Wmi.Query(Endpoint, query)) { var data = await q.GetFirstResultAsync().ConfigureAwait(false); if (data == null) { return; } var available = data.AvailableKBytes * 1024; MemoryUsed = TotalMemory - available; var utilization = new MemoryUtilization { DateEpoch = DateTime.UtcNow.ToEpochTime(), AvgMemoryUsed = MemoryUsed }; UpdateHistoryStorage(MemoryHistory, utilization); } }
public static ICollection <Processor> GetProcessors() { List <Processor> processorList = new List <Processor>(); string[] requiredProperties = new string[] { "CurrentClockSpeed", "CurrentVoltage", "Name", "Manufacturer", "NumberOfCores", "ProcessorId" }; WmiClassCollection classCollection = Wmi.Query(Wmi.PROCESSOR_CLASSNAME, requiredProperties); if (classCollection == null) { return(processorList); } foreach (WmiClass wmiClass in classCollection) { Processor processor = new Processor( (uint?)wmiClass["CurrentClockSpeed"].Value, (ushort?)wmiClass["CurrentVoltage"].Value, (string)wmiClass["Name"].Value, (string)wmiClass["Manufacturer"].Value, (uint?)wmiClass["NumberOfCores"].Value, (string)wmiClass["ProcessorId"].Value); processorList.Add(processor); } return(processorList); }
// Token: 0x0600005E RID: 94 RVA: 0x0000329F File Offset: 0x0000149F public static string GetSerialNumber() { return(Wmi.PropertyQuery <string>("Win32_OperatingSystem", "SerialNumber", null)); }
private Task <bool> GetIsVMHost() => Wmi.ClassExists(Endpoint, "Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor");
public static Win32Process?ById (uint processId, ManagementScope?managementScope = null) => Wmi .Query( $"SELECT * FROM {Win32Process.WmiClassName} WHERE {nameof(Win32Process.ProcessId)} = {processId}", managementScope) .Select(process => new Win32Process(process)).FirstOrDefault();
private async Task GetAllInterfacesAsync() { const string query = @" SELECT Name, PNPDeviceID, DeviceID, NetConnectionID, Description, MACAddress, Speed, InterfaceIndex FROM Win32_NetworkAdapter WHERE NetConnectionStatus = 2"; //connected adapters. //'AND PhysicalAdapter = True' causes exceptions with old windows versions. var indexMap = new Dictionary <uint, Interface>(); using (var q = Wmi.Query(Endpoint, query)) { foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false)) { string id = $"{data.DeviceID}"; var i = Interfaces.Find(x => x.Id == id) ?? new Interface(); indexMap[data.InterfaceIndex] = i; i.Id = id; i.Alias = "!alias"; i.Caption = data.NetConnectionID; i.FullName = data.Description; i.NodeId = Id; i.LastSync = DateTime.UtcNow; i.Name = await GetRealAdapterName(data.PNPDeviceID).ConfigureAwait(false); i.PhysicalAddress = data.MACAddress; i.Speed = data.Speed; i.Status = NodeStatus.Active; i.TypeDescription = ""; i.IPs = new List <IPNet>(); i.TeamMembers = new List <string>(); if (i.Node == null) { i.Node = this; Interfaces.Add(i); } } } if (_canQueryTeamingInformation) { const string teamsQuery = "SELECT InstanceID, Name FROM MSFT_NetLbfoTeam"; var teamNamesToInterfaces = new Dictionary <string, Interface>(); using (var q = Wmi.Query(Endpoint, teamsQuery, @"root\standardcimv2")) { foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false)) { var teamInterface = Interfaces.Find(x => x.Caption == data.Name); if (teamInterface == null) { continue; } teamNamesToInterfaces.Add(data.Name, teamInterface); } } const string teamMembersQuery = "SELECT InstanceID, Name, Team FROM MSFT_NetLbfoTeamMember"; using (var q = Wmi.Query(Endpoint, teamMembersQuery, @"root\standardcimv2")) { foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false)) { var teamName = data.Team; if (teamNamesToInterfaces.TryGetValue(teamName, out Interface teamInterface)) { var adapterName = data.Name; var memberInterface = Interfaces.Find(x => x.Name == adapterName); if (memberInterface == null) { continue; } teamInterface.TeamMembers.Add(memberInterface.Id); } } } } const string ipQuery = @" SELECT InterfaceIndex, IPAddress, IPSubnet, DHCPEnabled FROM WIn32_NetworkAdapterConfiguration WHERE IPEnabled = 'True'"; using (var q = Wmi.Query(Endpoint, ipQuery)) { foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false)) { if (indexMap.TryGetValue(data.InterfaceIndex, out Interface i)) { i.DHCPEnabled = data.DHCPEnabled; var ips = data.IPAddress as string[]; var subnets = data.IPSubnet as string[]; if (ips == null || subnets == null) { continue; } for (var j = 0; j < (ips?.Length).GetValueOrDefault(0); j++) { if (int.TryParse(subnets[j], out int cidr) && IPNet.TryParse(ips[j], cidr, out IPNet net)) { i.IPs.Add(net); } else if (IPNet.TryParse(ips[j], subnets[j], out net)) { i.IPs.Add(net); } } } } } }
public void ExecuteRemoteProcess(string command) { Wmi cimv2 = new Wmi(ServerNameSettings, "root\\cimv2"); ManagementClass objProcess = cimv2.GetWmiClass("Win32_Process"); // run process object[] methodArgs = { command, null, null, 0 }; objProcess.InvokeMethod("Create", methodArgs); // process ID int processId = Convert.ToInt32(methodArgs[3]); // wait until finished // Create event query to be notified within 1 second of // a change in a service WqlEventQuery query = new WqlEventQuery("__InstanceDeletionEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\""); // Initialize an event watcher and subscribe to events // that match this query ManagementEventWatcher watcher = new ManagementEventWatcher(cimv2.GetScope(), query); // times out watcher.WaitForNextEvent in 20 seconds watcher.Options.Timeout = new TimeSpan(0, 0, 20); // Block until the next event occurs // Note: this can be done in a loop if waiting for // more than one occurrence while (true) { ManagementBaseObject e = null; try { // wait untill next process finish e = watcher.WaitForNextEvent(); } catch { // nothing has been finished in timeout period return; // exit } // check process id int pid = Convert.ToInt32(((ManagementBaseObject)e["TargetInstance"])["ProcessID"]); if (pid == processId) { //Cancel the subscription watcher.Stop(); // exit return; } } }
// Token: 0x06000062 RID: 98 RVA: 0x000032E7 File Offset: 0x000014E7 public static string GetBootDevice() { return(Wmi.PropertyQuery <string>("Win32_OperatingSystem", "BootDevice", null)); }
public static string GetSerialNumber() => Wmi.PropertyQuery <string>(Wmi.BIOS_CLASSNAME, "SerialNumber");
public void DeleteFolder(string path) { if (path.StartsWith(@"\\")) { // network share try { FileUtils.DeleteFile(path); } catch { /* just skip */ } FileUtils.DeleteFile(path); } else { // local folder // delete sub folders first ManagementObjectCollection objSubFolders = GetSubFolders(path); foreach (ManagementObject objSubFolder in objSubFolders) DeleteFolder(objSubFolder["Name"].ToString()); // delete this folder itself Wmi cimv2 = new Wmi(ServerNameSettings, "root\\cimv2"); ManagementObject objFolder = cimv2.GetWmiObject("Win32_Directory", "Name='{0}'", path.Replace("\\", "\\\\")); objFolder.InvokeMethod("Delete", null); } }
public static string GetManufacturer() => Wmi.PropertyQuery <string>(Wmi.BIOS_CLASSNAME, "Manufacturer");
public static bool?IsPrimaryBios() => Wmi.PropertyQuery <bool?>(Wmi.BIOS_CLASSNAME, "PrimaryBIOS");
public static string GetName() => Wmi.PropertyQuery <string>(Wmi.BIOS_CLASSNAME, "Name");
private async Task GetAllInterfacesAsync() { const string query = @" SELECT Name, DeviceID, NetConnectionID, Description, MACAddress, Speed, InterfaceIndex FROM Win32_NetworkAdapter WHERE NetConnectionStatus = 2"; //connected adapters. //'AND PhysicalAdapter = True' causes exceptions with old windows versions. var indexMap = new Dictionary <uint, Interface>(); using (var q = Wmi.Query(Endpoint, query)) { foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false)) { string id = $"{data.DeviceID}"; var i = Interfaces.FirstOrDefault(x => x.Id == id); if (i == null) { i = new Interface(); Interfaces.Add(i); } indexMap[data.InterfaceIndex] = i; i.Id = $"{data.DeviceID}"; i.Alias = "!alias"; i.Caption = data.NetConnectionID == "Ethernet" ? data.Name : data.NetConnectionID; i.FullName = data.Description; i.NodeId = Id; i.LastSync = DateTime.UtcNow; i.Name = data.Name; i.PhysicalAddress = data.MACAddress; i.Speed = data.Speed; i.Status = NodeStatus.Active; i.TypeDescription = ""; i.IPs = new List <IPNet>(); } } const string ipQuery = @" Select InterfaceIndex, IPAddress, IPSubnet, DHCPEnabled From WIn32_NetworkAdapterConfiguration Where IPEnabled = 'True'"; using (var q = Wmi.Query(Endpoint, ipQuery)) { foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false)) { Interface i; if (indexMap.TryGetValue(data.InterfaceIndex, out i)) { i.DHCPEnabled = data.DHCPEnabled; string[] ips = data.IPAddress as string[], subnets = data.IPSubnet as string[]; for (var j = 0; j < (ips?.Length).GetValueOrDefault(0); j++) { IPNet net; int cidr; if (int.TryParse(subnets[j], out cidr) && IPNet.TryParse(ips[j], cidr, out net)) { i.IPs.Add(net); } else if (IPNet.TryParse(ips[j], subnets[j], out net)) { i.IPs.Add(net); } } } } } }
// Token: 0x06000068 RID: 104 RVA: 0x00003353 File Offset: 0x00001553 public static uint?GetNumberOfProcesses() { return(Wmi.PropertyQuery <uint?>("Win32_OperatingSystem", "NumberOfProcesses", null)); }
// Token: 0x0600005C RID: 92 RVA: 0x0000327B File Offset: 0x0000147B public static string GetCaption() { return(Wmi.PropertyQuery <string>("Win32_OperatingSystem", "Caption", null)); }
public static string GetDescription() => Wmi.PropertyQuery <string>(Wmi.BIOS_CLASSNAME, "Description");
public void DeleteFile(string path) { if (path.StartsWith(@"\\")) { // network share File.Delete(path); } else { // delete file using WMI Wmi cimv2 = new Wmi(ServerNameSettings, "root\\cimv2"); ManagementObject objFile = cimv2.GetWmiObject("CIM_Datafile", "Name='{0}'", path.Replace("\\", "\\\\")); objFile.InvokeMethod("Delete", null); } }
// Token: 0x06000064 RID: 100 RVA: 0x0000330B File Offset: 0x0000150B public static string GetSystemDrive() { return(Wmi.PropertyQuery <string>("Win32_OperatingSystem", "SystemDrive", null)); }
private ManagementObjectCollection GetSubFolders(string path) { if (path.EndsWith("\\")) path = path.Substring(0, path.Length - 1); Wmi cimv2 = new Wmi(ServerNameSettings, "root\\cimv2"); return cimv2.ExecuteWmiQuery("Associators of {Win32_Directory.Name='" + path + "'} " + "Where AssocClass = Win32_Subdirectory " + "ResultRole = PartComponent"); }
public static async void InstantInfoEquip(HttpListenerContext ctx) { WebSocketContext wsc; WebSocket ws; try { wsc = await ctx.AcceptWebSocketAsync(null); ws = wsc.WebSocket; } catch (WebSocketException ex) { ctx.Response.Close(); Logging.Err(ex); return; } string sessionId = ctx.Request.Cookies["sessionid"]?.Value ?? null; if (sessionId is null) { ctx.Response.Close(); return; } try { byte[] buff = new byte[2048]; WebSocketReceiveResult receiveResult = await ws.ReceiveAsync(new ArraySegment <byte>(buff), CancellationToken.None); string filename = Encoding.Default.GetString(buff, 0, receiveResult.Count); if (!Database.equip.ContainsKey(filename)) { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); return; } Database.DbEntry equip = (Database.DbEntry)Database.equip[filename]; string host = null; if (equip.hash.ContainsKey("IP")) { host = ((string[])equip.hash["IP"])[0]; } else if (equip.hash.ContainsKey("HOSTNAME")) { host = ((string[])equip.hash["HOSTNAME"])[0]; } else { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); return; } string lastseen = ""; string[] ipArray = host.Split(';').Select(o => o.Trim()).ToArray(); try { using System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); PingReply reply = p.Send(ipArray[0], 1000); if (reply.Status == IPStatus.Success) { lastseen = "Just now"; WsWriteText(ws, $"last seen{(char)127}{lastseen}{(char)127}ICMP"); WsWriteText(ws, $".roundtrip:{ipArray[0]}{(char)127}{reply.RoundtripTime}{(char)127}ICMP"); LastSeen.Seen(ipArray[0]); } else { lastseen = Encoding.UTF8.GetString(LastSeen.HasBeenSeen(ipArray[0], true)); WsWriteText(ws, $"last seen{(char)127}{lastseen}{(char)127}ICMP"); WsWriteText(ws, $".roundtrip:{ipArray[0]}{(char)127}TimedOut{(char)127}ICMP"); } } catch { WsWriteText(ws, $".roundtrip:{host}{(char)127}Error{(char)127}ICMP"); } if (ipArray.Length > 1) { for (int i = 1; i < ipArray.Length; i++) { try { using System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); PingReply reply = p.Send(ipArray[i], 1000); if (reply.Status == IPStatus.Success) { WsWriteText(ws, $".roundtrip:{ipArray[i]}{(char)127}{reply.RoundtripTime}{(char)127}ICMP"); } else { WsWriteText(ws, $".roundtrip:{ipArray[i]}{(char)127}{reply.Status}{(char)127}ICMP"); } } catch { WsWriteText(ws, $".roundtrip:{ipArray[i]}{(char)127}Error{(char)127}ICMP"); } } } List <string> warnings = new List <string>(); string wmiHostName = null, adHostName = null, netbios = null, dns = null; if (lastseen == "Just now") { ManagementScope scope = Wmi.WmiScope(host); if (scope != null) { string username = Wmi.WmiGet(scope, "Win32_ComputerSystem", "UserName", false, null); if (username.Length > 0) { WsWriteText(ws, $"logged in user{(char)127}{username}{(char)127}WMI"); } string starttime = Wmi.WmiGet(scope, "Win32_LogonSession", "StartTime", false, new Wmi.FormatMethodPtr(Wmi.DateTimeToString)); if (starttime.Length > 0) { WsWriteText(ws, $"start time{(char)127}{starttime}{(char)127}WMI"); } wmiHostName = Wmi.WmiGet(scope, "Win32_ComputerSystem", "DNSHostName", false, null); } using ManagementObjectCollection logicalDisk = new ManagementObjectSearcher(scope, new SelectQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3")).Get(); foreach (ManagementObject o in logicalDisk) { string caption = o.GetPropertyValue("Caption").ToString(); UInt64 size = (UInt64)o.GetPropertyValue("Size"); UInt64 free = (UInt64)o.GetPropertyValue("FreeSpace"); if (size == 0) { continue; } UInt64 percent = 100 * free / size; if (percent < 10) { warnings.Add($"{percent}% free space on disk {caption}"); } } } if (equip.hash.ContainsKey("HOSTNAME")) { string hostname = ((string[])equip.hash["HOSTNAME"])[0]; SearchResult result = ActiveDirectory.GetWorkstation(hostname); if (result != null) { if (result.Properties["lastLogonTimestamp"].Count > 0) { string time = ActiveDirectory.FileTimeString(result.Properties["lastLogonTimestamp"][0].ToString()); if (time.Length > 0) { WsWriteText(ws, $"last logon{(char)127}{time}{(char)127}Active directory"); } } if (result.Properties["lastLogoff"].Count > 0) { string time = ActiveDirectory.FileTimeString(result.Properties["lastLogoff"][0].ToString()); if (time.Length > 0) { WsWriteText(ws, $"last logoff{(char)127}{time}{(char)127}Active directory"); } } if (result.Properties["dNSHostName"].Count > 0) { adHostName = result.Properties["dNSHostName"][0].ToString(); } } } try { dns = (await System.Net.Dns.GetHostEntryAsync(host)).HostName; } catch { } if (!(dns is null)) { dns = dns?.Split('.')[0].ToUpper(); bool mismatch = false; if (!mismatch && !(wmiHostName is null) && wmiHostName.Length > 0) { wmiHostName = wmiHostName?.Split('.')[0].ToUpper(); if (wmiHostName != dns) { warnings.Add($"DNS mismatch: {wmiHostName} ≠ {dns}"); mismatch = true; } } if (!mismatch && !(adHostName is null) && adHostName.Length > 0) { adHostName = adHostName?.Split('.')[0].ToUpper(); if (adHostName != dns) { warnings.Add($"DNS mismatch: {adHostName} ≠ {dns}"); mismatch = true; } } if (!mismatch && wmiHostName is null && adHostName is null) { netbios = await NetBios.GetBiosNameAsync(host); } if (!mismatch && !(netbios is null) && netbios.Length > 0) { netbios = netbios?.Split('.')[0].ToUpper(); if (netbios != dns) { warnings.Add($"DNS mismatch: {netbios} ≠ {dns}"); mismatch = true; } } } for (int i = 0; i < warnings.Count; i++) { WsWriteText(ws, $"!{(char)127}{warnings[i]}{(char)127}"); } try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } catch { } } catch (Exception ex) { Logging.Err(ex); } }
public string GetTempRemoteFolder() { Wmi cimv2 = new Wmi(ServerNameSettings, "root\\cimv2"); ManagementObject objOS = cimv2.GetWmiObject("win32_OperatingSystem"); string sysPath = (string)objOS["SystemDirectory"]; // remove trailing slash if (sysPath.EndsWith("\\")) sysPath = sysPath.Substring(0, sysPath.Length - 1); sysPath = sysPath.Substring(0, sysPath.LastIndexOf("\\") + 1) + "Temp"; return sysPath; }
public List<VirtualSwitch> GetExternalSwitches(string computerName) { Wmi cwmi = new Wmi(computerName, WMI_VIRTUALIZATION_NAMESPACE); Dictionary<string, string> switches = new Dictionary<string, string>(); List<VirtualSwitch> list = new List<VirtualSwitch>(); // load external adapters Dictionary<string, string> adapters = new Dictionary<string, string>(); ManagementObjectCollection objAdapters = cwmi.GetWmiObjects("Msvm_ExternalEthernetPort"); foreach (ManagementObject objAdapter in objAdapters) adapters.Add((string)objAdapter["DeviceID"], "1"); // get active connections ManagementObjectCollection objConnections = cwmi.GetWmiObjects("Msvm_ActiveConnection"); foreach (ManagementObject objConnection in objConnections) { // check LAN andpoint ManagementObject objLanEndpoint = new ManagementObject(new ManagementPath((string)objConnection["Dependent"])); string endpointName = (string)objLanEndpoint["Name"]; if (!endpointName.StartsWith("/DEVICE/")) continue; endpointName = endpointName.Substring(8); if (adapters.ContainsKey(endpointName)) { // get switch port ManagementObject objPort = new ManagementObject(new ManagementPath((string)objConnection["Antecedent"])); string switchId = (string)objPort["SystemName"]; if (switches.ContainsKey(switchId)) continue; // add info about switch ManagementObject objSwitch = cwmi.GetRelatedWmiObject(objPort, "Msvm_VirtualSwitch"); switches.Add(switchId, (string)objSwitch["ElementName"]); } } foreach (string switchId in switches.Keys) { VirtualSwitch sw = new VirtualSwitch(); sw.SwitchId = switchId; sw.Name = switches[switchId]; list.Add(sw); } return list; }
public static IEnumerable <Win32Process> All (ManagementScope?managementScope = null) => Wmi .Query($"SELECT * FROM {Win32Process.WmiClassName}", managementScope) .Select(process => new Win32Process(process));
private async Task UpdateNodeDataAsync() { const string machineQuery = @"SELECT DNSHostName, Domain, Manufacturer, Model, NumberOfLogicalProcessors FROM Win32_ComputerSystem"; using (var q = Wmi.Query(Endpoint, machineQuery)) { var data = await q.GetFirstResultAsync().ConfigureAwait(false); if (data != null) { Model = data.Model; Manufacturer = data.Manufacturer; // Only use domain if we're on one - not for things like workgroups Name = _machineDomainName.HasValue() && data.Domain != _machineDomainName ? $"{data.DNSHostName}.{data.Domain}" : data.DNSHostName; NumberOfLogicalProcessors = data.NumberOfLogicalProcessors; } } const string query = @"SELECT Caption, LastBootUpTime, Version, FreePhysicalMemory, TotalVisibleMemorySize, Version FROM Win32_OperatingSystem"; using (var q = Wmi.Query(Endpoint, query)) { var data = await q.GetFirstResultAsync().ConfigureAwait(false); if (data != null) { LastBoot = ManagementDateTimeConverter.ToDateTime(data.LastBootUpTime); TotalMemory = data.TotalVisibleMemorySize * 1024; MemoryUsed = TotalMemory - (data.FreePhysicalMemory * 1024); KernelVersion = Version.Parse(data.Version); MachineType = data.Caption.ToString() + " " + data.Version.ToString(); } } const string servicetagquery = @"SELECT SerialNumber FROM Win32_BIOS"; using (var q = Wmi.Query(Endpoint, servicetagquery)) { var data = await q.GetFirstResultAsync().ConfigureAwait(false); if (data != null) { ServiceTag = data.SerialNumber; } } LastSync = DateTime.UtcNow; Status = NodeStatus.Active; IsVMHost = await GetIsVMHost().ConfigureAwait(false); _canQueryAdapterUtilization = await GetCanQueryAdapterUtilization().ConfigureAwait(false); _canQueryTeamingInformation = await Wmi.ClassExists(Endpoint, "MSFT_NetLbfoTeamMember", @"root\standardcimv2").ConfigureAwait(false); }
public static IEnumerable <Win32Process> ByName (string name, ManagementScope?managementScope = null) => Wmi .Query( $"SELECT * FROM {Win32Process.WmiClassName} WHERE {nameof(Win32Process.Name)} = '{name}'", managementScope) .Select(process => new Win32Process(process));
public static string GetCaption() => Wmi.PropertyQuery <string>(Wmi.OPERATINGSYSTEM_CLASSNAME, "Caption");
// Token: 0x06000061 RID: 97 RVA: 0x000032D5 File Offset: 0x000014D5 public static DateTime?GetLocalDateTime() { return(Wmi.PropertyQuery <DateTime?>("Win32_OperatingSystem", "LocalDateTime", null)); }
public bool DirectoryExists(string path) { if (path.StartsWith(@"\\")) // network share return Directory.Exists(path); else { Wmi cimv2 = new Wmi(ServerNameSettings, WMI_CIMV2_NAMESPACE); ManagementObject objDir = cimv2.GetWmiObject("Win32_Directory", "Name='{0}'", path.Replace("\\", "\\\\")); return (objDir != null); } }
// Token: 0x0600005D RID: 93 RVA: 0x0000328D File Offset: 0x0000148D public static string GetOSArchitecture() { return(Wmi.PropertyQuery <string>("Win32_OperatingSystem", "OSArchitecture", null)); }
public bool CopyFile(string sourceFileName, string destinationFileName) { Log.WriteInfo("Copy file - source: " + sourceFileName); Log.WriteInfo("Copy file - destination: " + destinationFileName); if (sourceFileName.StartsWith(@"\\")) // network share { if (!File.Exists(sourceFileName)) return false; File.Copy(sourceFileName, destinationFileName); } else { if (!FileExists(sourceFileName)) return false; // copy using WMI Wmi cimv2 = new Wmi(ServerNameSettings, WMI_CIMV2_NAMESPACE); ManagementObject objFile = cimv2.GetWmiObject("CIM_Datafile", "Name='{0}'", sourceFileName.Replace("\\", "\\\\")); if (objFile == null) throw new Exception("Source file does not exists: " + sourceFileName); objFile.InvokeMethod("Copy", new object[] { destinationFileName }); } return true; }
public MountedDiskInfo MountVirtualHardDisk(string vhdPath) { ManagementObject objImgSvc = GetImageManagementService(); // get method params ManagementBaseObject inParams = objImgSvc.GetMethodParameters("Mount"); inParams["Path"] = FileUtils.EvaluateSystemVariables(vhdPath); ManagementBaseObject outParams = (ManagementBaseObject)objImgSvc.InvokeMethod("Mount", inParams, null); JobResult result = CreateJobResultFromWmiMethodResults(outParams); // load storage job if (result.ReturnValue != ReturnCode.JobStarted) throw new Exception("Failed to start Mount job with the following error: " + result.ReturnValue); ; ManagementObject objJob = wmi.GetWmiObject("msvm_StorageJob", "InstanceID = '{0}'", result.Job.Id); if (!JobCompleted(result.Job)) throw new Exception("Failed to complete Mount job with the following error: " + result.Job.ErrorDescription); try { List<string> volumes = new List<string>(); // load output data ManagementObject objImage = wmi.GetRelatedWmiObject(objJob, "Msvm_MountedStorageImage"); int pathId = Convert.ToInt32(objImage["PathId"]); int portNumber = Convert.ToInt32(objImage["PortNumber"]); int targetId = Convert.ToInt32(objImage["TargetId"]); int lun = Convert.ToInt32(objImage["Lun"]); string diskAddress = String.Format("Port{0}Path{1}Target{2}Lun{3}", portNumber, pathId, targetId, lun); Log.WriteInfo("Disk address: " + diskAddress); // find mounted disk using VDS Vds.Advanced.AdvancedDisk advancedDisk = null; Vds.Pack diskPack = null; // first attempt System.Threading.Thread.Sleep(3000); Log.WriteInfo("Trying to find mounted disk - first attempt"); FindVdsDisk(diskAddress, out advancedDisk, out diskPack); // second attempt if (advancedDisk == null) { System.Threading.Thread.Sleep(20000); Log.WriteInfo("Trying to find mounted disk - second attempt"); FindVdsDisk(diskAddress, out advancedDisk, out diskPack); } if (advancedDisk == null) throw new Exception("Could not find mounted disk"); // check if DiskPart must be used to bring disk online and clear read-only flag bool useDiskPartToClearReadOnly = false; if (ConfigurationManager.AppSettings[CONFIG_USE_DISKPART_TO_CLEAR_READONLY_FLAG] != null) useDiskPartToClearReadOnly = Boolean.Parse(ConfigurationManager.AppSettings[CONFIG_USE_DISKPART_TO_CLEAR_READONLY_FLAG]); // determine disk index for DiskPart Wmi cimv2 = new Wmi(ServerNameSettings, WMI_CIMV2_NAMESPACE); ManagementObject objDisk = cimv2.GetWmiObject("win32_diskdrive", "Model='Msft Virtual Disk SCSI Disk Device' and ScsiTargetID={0} and ScsiLogicalUnit={1} and scsiPort={2}", targetId, lun, portNumber); if (useDiskPartToClearReadOnly) { // *** Clear Read-Only and bring disk online with DiskPart *** Log.WriteInfo("Clearing disk Read-only flag and bringing disk online"); if (objDisk != null) { // disk found // run DiskPart string diskPartResult = RunDiskPart(String.Format(@"select disk {0} attributes disk clear readonly online disk exit", Convert.ToInt32(objDisk["Index"]))); Log.WriteInfo("DiskPart Result: " + diskPartResult); } } else { // *** Clear Read-Only and bring disk online with VDS *** // clear Read-Only if ((advancedDisk.Flags & Vds.DiskFlags.ReadOnly) == Vds.DiskFlags.ReadOnly) { Log.WriteInfo("Clearing disk Read-only flag"); advancedDisk.ClearFlags(Vds.DiskFlags.ReadOnly); while ((advancedDisk.Flags & Vds.DiskFlags.ReadOnly) == Vds.DiskFlags.ReadOnly) { System.Threading.Thread.Sleep(100); advancedDisk.Refresh(); } } // bring disk ONLINE if (advancedDisk.Status == Vds.DiskStatus.Offline) { Log.WriteInfo("Bringing disk online"); advancedDisk.Online(); while (advancedDisk.Status == Vds.DiskStatus.Offline) { System.Threading.Thread.Sleep(100); advancedDisk.Refresh(); } } } // small pause after getting disk online System.Threading.Thread.Sleep(3000); // get disk again FindVdsDisk(diskAddress, out advancedDisk, out diskPack); // find volumes using VDS Log.WriteInfo("Querying disk volumes with VDS"); foreach (Vds.Volume volume in diskPack.Volumes) { string letter = volume.DriveLetter.ToString(); if (letter != "") volumes.Add(letter); } // find volumes using WMI if (volumes.Count == 0 && objDisk != null) { Log.WriteInfo("Querying disk volumes with WMI"); foreach (ManagementObject objPartition in objDisk.GetRelated("Win32_DiskPartition")) { foreach (ManagementObject objVolume in objPartition.GetRelated("Win32_LogicalDisk")) { volumes.Add(objVolume["Name"].ToString().TrimEnd(':')); } } } Log.WriteInfo("Volumes found: " + volumes.Count); // info object MountedDiskInfo info = new MountedDiskInfo(); info.DiskAddress = diskAddress; info.DiskVolumes = volumes.ToArray(); return info; } catch (Exception ex) { // unmount disk UnmountVirtualHardDisk(vhdPath); // throw error throw ex; } }
// Token: 0x06000066 RID: 102 RVA: 0x0000332F File Offset: 0x0000152F public static string GetWindowsDirectory() { return(Wmi.PropertyQuery <string>("Win32_OperatingSystem", "WindowsDirectory", null)); }
/// <summary> /// Start Net Tcp Port sharing service on server /// Open FBService port on firewall /// Create remove clients /// Execute clients via WMI /// </summary> private static void CreateClients() { Wmi.StartNetTcpPortSharing(); Wmi.OpenPortOnFireWall(); Wmi.CreateClientAgents(); }
public bool FileExists(string path) { Log.WriteInfo("Check remote file exists: " + path); if (path.StartsWith(@"\\")) // network share return File.Exists(path); else { Wmi cimv2 = new Wmi(ServerNameSettings, WMI_CIMV2_NAMESPACE); ManagementObject objFile = cimv2.GetWmiObject("CIM_Datafile", "Name='{0}'", path.Replace("\\", "\\\\")); return (objFile != null); } }