/// <summary> /// The start detection. /// </summary> /// <param name="action"> /// The detection Action. /// </param> public void StartDetection(Action action) { ThreadPool.QueueUserWorkItem( delegate { this.detectionAction = action; var options = new ConnectionOptions { EnablePrivileges = true }; var scope = new ManagementScope(@"root\CIMV2", options); try { var query = new WqlEventQuery { EventClassName = "__InstanceModificationEvent", WithinInterval = TimeSpan.FromSeconds(1), Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5" // DriveType - 5: CDROM }; this.watcher = new ManagementEventWatcher(scope, query); this.watcher.EventArrived += this.WatcherEventArrived; this.watcher.Start(); } catch (Exception e) { Console.WriteLine(e.Message); } }); }
//private char NULL_VALUE = char(0); public static ProcessReturnCode Run(string machineName, string commandLine, string args, string currentDirectory) { var connOptions = new ConnectionOptions { EnablePrivileges = true }; var scope = new ManagementScope(@"\\{0}\root\cimv2".FormatWith(machineName), connOptions); scope.Connect(); var managementPath = new ManagementPath(CLASSNAME); using (var processClass = new ManagementClass(scope, managementPath, new ObjectGetOptions())) { var inParams = processClass.GetMethodParameters("Create"); commandLine = System.IO.Path.Combine(currentDirectory, commandLine); inParams["CommandLine"] = "{0} {1}".FormatWith(commandLine, args); var outParams = processClass.InvokeMethod("Create", inParams, null); var rtn = Convert.ToUInt32(outParams["returnValue"]); var pid = Convert.ToUInt32(outParams["processId"]); if (pid != 0) { WaitForPidToDie(machineName, pid); } return (ProcessReturnCode)rtn; } }
public static string ShowUserSID(string username) { // local scope string[] unames = username.Split("\\".ToCharArray(),2); string d = ""; string n = ""; d = unames[0]; if (unames.Length < 2) { n = unames[0]; d = "US_IBS"; } else n = unames[1]; ConnectionOptions co = new ConnectionOptions(); //co.Username = username; ManagementScope msc = new ManagementScope ("\\root\\cimv2",co); string queryString = "SELECT * FROM Win32_UserAccount where LocalAccount = false AND SIDType = 1 AND Domain = '" + d+ "' AND Name = '" + n + "'"; //System.Windows.Forms.MessageBox.Show(queryString); SelectQuery q = new SelectQuery (queryString); query = new ManagementObjectSearcher(msc, q); queryCollection = query.Get(); string res=String.Empty; foreach( ManagementObject mo in queryCollection ) { // there should be only one here! res+= mo["SID"].ToString(); //res+= mo["Name"]+"\n"; } return res; }
protected virtual void GetOperatingSystemInfo(string Name, string UserName, string Password) { if (string.IsNullOrEmpty(Name)) throw new ArgumentNullException("Name"); ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempNetworkAdapter in Collection) { if (TempNetworkAdapter.Properties["LastBootUpTime"].Value != null) { LastBootUpTime = ManagementDateTimeConverter.ToDateTime(TempNetworkAdapter.Properties["LastBootUpTime"].Value.ToString()); } } } } }
static void Main(string[] args) { ConnectionOptions conn = new ConnectionOptions(); conn.Username = "******";//登入远端电脑的账户 conn.Password = "******";//登入远端电脑的密码 ManagementPath path = new ManagementPath(); //其中root\cimv2是固定写法 path.Path = @"\\10.0.1.36\root\cimv2"; ManagementScope ms = new ManagementScope(); ms.Options = conn; ms.Path = path; ms.Connect(); //这里的例子读取文件的最后修改日期 ObjectQuery query = new ObjectQuery("SELECT * FROM CIM_DataFile WHERE Name = 'C:\\\\KVOffice.txt'"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms,query); ManagementObjectCollection collection = searcher.Get(); string time = ""; foreach (ManagementObject obj in collection) { time = obj.Properties["LastModified"].Value.ToString().Substring(0,14); } Console.WriteLine("测试dev"); Console.WriteLine(time); Console.ReadLine(); }
public DriveService() { // Bind to local machine var options = new ConnectionOptions { EnablePrivileges = true }; var scope = new ManagementScope(@"root\CIMV2", options); try { var query = new WqlEventQuery { EventClassName = "__InstanceModificationEvent", WithinInterval = TimeSpan.FromSeconds(1), Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5" // DriveType - 5: CDROM }; this.watcher = new ManagementEventWatcher(scope, query); // register async. event handler this.watcher.EventArrived += this.HandleDiscEvent; this.watcher.Start(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } }
static void Main(string[] args) { try { string ComputerName = "localhost"; ManagementScope Scope; if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { ConnectionOptions Conn = new ConnectionOptions(); Conn.Username = ""; Conn.Password = ""; Conn.Authority = "ntlmdomain:DOMAIN"; Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn); } else Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null); Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_DiskDrive"); ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query); foreach (ManagementObject WmiObject in Searcher.Get()) { Console.WriteLine("{0,-35} {1,-40}","Name",WmiObject["Name"]);// String } } catch (Exception e) { Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace)); } Console.WriteLine("Press Enter to exit"); Console.Read(); }
/// <summary> /// Return the SID associated to a username /// </summary> /// <param name="userName">SID of username to get.</param> /// <returns>Return a string like S-1-5-21-1844237615-73586283-725345543-1003</returns> public static string GetUserSid (string userName) { ManagementObjectSearcher query; ManagementObjectCollection queryCollection; // local scope ConnectionOptions co = new ConnectionOptions(); co.Username = userName; ManagementScope msc = new ManagementScope ("\\root\\cimv2",co); string queryString = "SELECT * FROM Win32_UserAccount where name='" +co.Username +"'"; SelectQuery q = new SelectQuery (queryString); query = new ManagementObjectSearcher(msc, q); queryCollection = query.Get(); /* string res = StringUtility.CreateEmptyString (); foreach(ManagementObject mo in queryCollection) { // there should be only one here! res+= mo["SID"].ToString(); } */ StringBuilder LocalStringBuilder = new StringBuilder(); foreach(ManagementObject mo in queryCollection) { LocalStringBuilder.Append (mo["SID"].ToString ()); } return LocalStringBuilder.ToString (); }
public void Start(PagesPrinted callback) { Printed += callback; try { ManagementScope scope; if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { var conn = new ConnectionOptions(); conn.Username = ""; conn.Password = ""; conn.Authority = "ntlmdomain:DOMAIN"; scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), conn); } else { scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null); } scope.Connect(); _watcher = new ManagementEventWatcher(scope, new EventQuery(WmiQuery)); _watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler); _watcher.Start(); } catch (Exception e) { Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace); } }
public ManagementClass GetManagementClass(string scopeString, string classString, IPHostEntry hostEntry, string username, string password) { SetHost(hostEntry); ValidateHost(); var connectionOptions = new ConnectionOptions() { Impersonation = ImpersonationLevel.Impersonate, EnablePrivileges = true, Username = username, Password = password }; var managementScope = new ManagementScope(String.Format(@"\\{0}\{1}", _host, scopeString), connectionOptions); var managementClass = new ManagementClass(managementScope, new ManagementPath(classString), new ObjectGetOptions()); managementScope.Connect(); if (!managementScope.IsConnected) { throw new InstrumentationException(ExceptionMessages.ScopeConnectFail); } return managementClass; }
public static bool ConnectWMIScope(string RemoteServer, string UserName, String Password) { bool retval = true; try { ConnectionOptions options = new ConnectionOptions(); options.EnablePrivileges = true; options.Impersonation = ImpersonationLevel.Impersonate; options.Authentication = AuthenticationLevel.Packet; options.Username = UserName; options.Password = Password; options.Timeout = TimeSpan.FromSeconds(2); string ConnectionString = string.Format("\\\\{0}\\root\\cimv2", RemoteServer); ManagementScope scope = new ManagementScope(ConnectionString, options); scope.Connect(); } catch (Exception ex) { MessageBox.Show(ex.Message); retval = false; return retval; } return retval; }
public static void StartService(string service) { string msg = string.Format("starting up service begins: {0}", service); Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg); string objPath = string.Format("Win32_Service.Name='{0}'", service); try { ConnectionOptions connectionOptions = new ConnectionOptions(); connectionOptions.Authentication = AuthenticationLevel.Packet; connectionOptions.EnablePrivileges = true; connectionOptions.Username = Singleton<Constants>.UniqueInstance.UserName; connectionOptions.Password = Singleton<Constants>.UniqueInstance.PassWord; connectionOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", Singleton<Constants>.UniqueInstance.MachineName), connectionOptions); scope.Connect(); using (ManagementObject serviceObj = new ManagementObject(scope, new ManagementPath(objPath), null)) { ManagementBaseObject outParams = serviceObj.InvokeMethod("StartService", null, null); uint returnValue = (uint)outParams["ReturnValue"]; msg = string.Format("starting up result for service {0} is {1}", service, returnValue); Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg, LogLevel.Warning); } } catch (Exception ex) { msg = string.Format("error starting up service: {0}, {1}", service, ex); Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg, LogLevel.Warning); } msg = string.Format("starting up service ends: {0}", service); Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg); }
public string GetMachineName() { string sBoxName = null; this.sQuery = "select CSName from Win32_OperatingSystem"; ConnectionOptions oXn = new ConnectionOptions(); ManagementScope oScope = new ManagementScope("\\\\localhost", oXn); ObjectQuery oQuery = new ObjectQuery(this.sQuery); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oScope, oQuery); ManagementObjectCollection oResults = oSearcher.Get(); foreach (ManagementObject oResult in oResults) { try { sBoxName = oResult["CSName"].ToString(); Logger.WriteEvent("Computer name: " + sBoxName, ZifliService._DEBUG); } catch { Logger.WriteEvent("Computer name is indeterminable.", ZifliService._WARN); } } return sBoxName; }
public static String[] getComputerInfos(string computername) { String[] computerInfos = new String[2]; ConnectionOptions connOptions = new ConnectionOptions(); ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementPath managementPath = new ManagementPath("Win32_Process"); //To use caller credential connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", computername), connOptions); manScope.Connect(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, query); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection){ computerInfos[0] = Convert.ToString(m["Caption"]); computerInfos[1] = Convert.ToString(m["Status"]); } return computerInfos; }
private void tsbRun_Click(object sender, EventArgs e) { SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject os in searcher.Get()) { this.txtResult.AppendText(os["Name"] + ";"); } this.txtResult.AppendText("\r\n"); //连接远程计算机 ConnectionOptions co = new ConnectionOptions(); co.Username = "******"; co.Password = "******"; System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\192.168.100.51\\root\\cimv2", co); //查询远程计算机 System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms, oq); ManagementObjectCollection queryCollection1 = query1.Get(); foreach (ManagementObject mo in queryCollection1) { string[] ss = { "" }; mo.InvokeMethod("Reboot", ss); this.txtResult.AppendText(mo.ToString()); } }
public static string getUserName() { try { var x = ""; var connectionOptions = new ConnectionOptions(); var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions); var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem"); using (var searcher = new ManagementObjectSearcher(scope, query)) { var builder = new System.Text.StringBuilder(); builder.Append(x); foreach (var row in searcher.Get()) { builder.Append((row["UserName"].ToString() + " ")); } x = builder.ToString(); return x; } } catch (Exception ex) { return ""; } }
public override void Install(System.Collections.IDictionary savedState) { try { base.Install(savedState); // Turn on "Allow service to interact with desktop". // (Note: A published technique to do this by setting a bit in the service's Type registry value (0x100) does not turn this on, so do as follows.) // This will let the NotifyIcon appear in the sys tray (with balloon at start-up), but not its context menu. ConnectionOptions options = new ConnectionOptions(); options.Impersonation = ImpersonationLevel.Impersonate; ManagementScope scope = new ManagementScope(@"root\CIMv2", options); // Common Information Model, version 2. ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + this.serviceInstaller.ServiceName + "'"); ManagementBaseObject inParameters = wmiService.GetMethodParameters("Change"); inParameters["DesktopInteract"] = true; ManagementBaseObject outParameters = wmiService.InvokeMethod("Change", inParameters, null); } catch (Exception e) { string licenseKey = ""; string licenseName = ""; try { licenseKey = Properties.Settings.Default.LicenseKey; licenseName = Properties.Settings.Default.LicenseName; } catch { } Service.Services.LoggingService.AddLogEntry(WOSI.CallButler.ManagementInterface.LogLevel.ErrorsOnly, Utils.ErrorUtils.FormatErrorString(e), true); CallButler.ExceptionManagement.ErrorCaptureUtils.SendError(e, licenseKey, licenseName, ""); } }
/// <summary> /// Gets the version of the OS for the given machine. /// </summary> /// <param name="machineName">The machine name.</param> /// <param name="userName">The username.</param> /// <param name="password">The password.</param> /// <returns>The OS version.</returns> public static Version GetVersion(string machineName, string userName, string password) { ConnectionOptions connectionOptions = new ConnectionOptions(); connectionOptions.Username = userName; connectionOptions.Password = password; return GetVersion(machineName, connectionOptions); }
protected override void OnCommitted(IDictionary savedState) { base.OnCommitted (savedState); // Setting the "Allow Interact with Desktop" option for this service. ConnectionOptions connOpt = new ConnectionOptions(); connOpt.Impersonation = ImpersonationLevel.Impersonate; ManagementScope mgmtScope = new ManagementScope(@"root\CIMv2", connOpt); mgmtScope.Connect(); ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ReflectorMgr.ReflectorServiceName + "'"); ManagementBaseObject inParam = wmiService.GetMethodParameters("Change"); inParam["DesktopInteract"] = true; ManagementBaseObject outParam = wmiService.InvokeMethod("Change", inParam, null); #region Start the reflector service immediately try { ServiceController sc = new ServiceController("ConferenceXP Reflector Service"); sc.Start(); } catch (Exception ex) { // Don't except - that would cause a rollback. Instead, just tell the user. RtlAwareMessageBox.Show(null, string.Format(CultureInfo.CurrentCulture, Strings.ServiceStartFailureText, ex.ToString()), Strings.ServiceStartFailureTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0); } #endregion }
private static void CallWmiShutdown(int flags) { // 実行前にガベージコレクトを行っておく GC.Collect(); System.Threading.Thread.CurrentThread.Join(0); GC.WaitForPendingFinalizers(); GC.Collect(); //ユーザー特権を有効にするための設定を作成 ConnectionOptions co = new ConnectionOptions(); co.Impersonation = ImpersonationLevel.Impersonate; co.EnablePrivileges = true; //ManagementScopeを作成 ManagementScope sc = new ManagementScope("\\ROOT\\CIMV2", co); //接続 sc.Connect(); ObjectQuery oq = new ObjectQuery("select * from Win32_OperatingSystem"); using (ManagementObjectSearcher mos = new ManagementObjectSearcher(sc, oq)) { //Shutdownメソッドを呼び出す foreach (ManagementObject mo in mos.Get()) { //パラメータを指定 ManagementBaseObject inParams = mo.GetMethodParameters("Win32Shutdown"); inParams["Flags"] = flags; inParams["Reserved"] = 0; //Win32Shutdownメソッドを呼び出す ManagementBaseObject outParams = mo.InvokeMethod("Win32Shutdown", inParams, null); } } }
private static ConnectionOptions GetConnectOptions(string machineName) { var co = new ConnectionOptions(); if (machineName == Environment.MachineName) return co; switch (machineName) { case "localhost": case "127.0.0.1": case "::1": return co; default: co = new ConnectionOptions { Authentication = AuthenticationLevel.Packet, Timeout = new TimeSpan(0, 0, 30), EnablePrivileges = true }; break; } var wps = Current.Settings.Polling.Windows; if (wps != null && wps.AuthUser.HasValue() && wps.AuthPassword.HasValue()) { co.Username = wps.AuthUser; co.Password = wps.AuthPassword; } return co; }
public void Bob() { var connOptions = new ConnectionOptions { EnablePrivileges = true, //Username = "******", //Password = "******" }; string server = "SrvTestWeb01"; ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", server), connOptions); manScope.Connect(); var managementPath = new ManagementPath("Win32_Process"); var processClass = new ManagementClass(manScope, managementPath, new ObjectGetOptions()); var inParams = processClass.GetMethodParameters("Create"); inParams["CommandLine"] = @"C:\Temp\dropkick.remote\dropkick.remote.exe create_queue msmq://localhost/dk_test"; var outParams = processClass.InvokeMethod("Create", inParams, null); var rtn = System.Convert.ToUInt32(outParams["returnValue"]); var processID = System.Convert.ToUInt32(outParams["processId"]); }
private ManagementScope ConnectToClient(string hostname) { ManagementPath oPath = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CCM", hostname)); ConnectionOptions oCon = new ConnectionOptions(); oCon.Impersonation = ImpersonationLevel.Impersonate; oCon.EnablePrivileges = true; ManagementScope oMs = new ManagementScope(oPath, oCon); try { oMs.Connect(); } catch (System.UnauthorizedAccessException ex) { return null; } catch (Exception e) { return null; } finally { GC.Collect(); } return oMs; }
/// <summary> /// Create and connect a management scope for use by subclasses /// </summary> /// <param name="path">The management path</param> protected WmiObjectBase(string path) { ConnectionOptions connectionOptions = new ConnectionOptions(); connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy; this.Scope = new ManagementScope(path, connectionOptions); this.Scope.Connect(); }
public static List<Object[]> checkAntiVirus() { List<Object[]> av = new List<Object[]>(); ConnectionOptions _connectionOptions = new ConnectionOptions(); _connectionOptions.EnablePrivileges = true; _connectionOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope _managementScope = new ManagementScope(string.Format("\\\\{0}\\root\\SecurityCenter2", "localhost"), _connectionOptions); _managementScope.Connect(); ObjectQuery _objectQuery = new ObjectQuery("SELECT * FROM AntivirusProduct"); ManagementObjectSearcher _managementObjectSearcher = new ManagementObjectSearcher(_managementScope, _objectQuery); ManagementObjectCollection _managementObjectCollection = _managementObjectSearcher.Get(); if (_managementObjectCollection.Count > 0) { Boolean updated = false; foreach (ManagementObject item in _managementObjectCollection) { updated = (item["productState"].ToString() == "266240" || item["productState"].ToString() == "262144"); av.Add(new Object[] { item["displayName"].ToString(), updated }); } } return av; }
/// <summary> /// Executes the specified function /// </summary> /// <param name="function">Function to execute</param> private void Execute(string function) { var options = new ConnectionOptions { Username = User, Password = Password, Authentication = AuthenticationLevel.PacketPrivacy }; var mgmtPath = new ManagementPath { Server = Server, NamespacePath = "root/MicrosoftIISv2" }; var mgmtScope = new ManagementScope(mgmtPath, options); mgmtScope.Connect(); var siteId = GetSiteIdFromWebSiteName(); if (!string.IsNullOrEmpty(siteId)) { var selectQuery = new SelectQuery("SELECT * FROM IIsWebServer WHERE Name = 'W3SVC/" + siteId + "'"); using (var managementObjectSearcher = new ManagementObjectSearcher(mgmtScope, selectQuery)) { foreach (ManagementObject objMgmt in managementObjectSearcher.Get()) { objMgmt.InvokeMethod(function, new object[0]); } } } }
/// <summary> /// Gets a list of files on the machine with a specific extension /// </summary> /// <param name="Computer">Computer to search</param> /// <param name="UserName">User name (if not local)</param> /// <param name="Password">Password (if not local)</param> /// <param name="Extension">File extension to look for</param> /// <returns>List of files that are found to have the specified extension</returns> public static IEnumerable<string> GetFilesWithExtension(string Computer, string UserName, string Password, string Extension) { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Computer), "Computer"); Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Extension), "Extension"); List<string> Files = new List<string>(); ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM CIM_DataFile where Extension='" + Extension + "'"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempBIOS in Collection) { Files.Add(TempBIOS.Properties["Drive"].Value.ToString()+TempBIOS.Properties["Path"].Value.ToString()+TempBIOS.Properties["FileName"].Value.ToString()); } } } return Files; }
/// <summary> /// Loads the BIOS info /// </summary> /// <param name="Name">Computer name</param> /// <param name="UserName">User name</param> /// <param name="Password">Password</param> private void LoadBIOS(string Name, string UserName, string Password) { ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_BIOS"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempBIOS in Collection) { SerialNumber = TempBIOS.Properties["Serialnumber"].Value.ToString(); } } } }
public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path) { ManagementScope connectScope = new ManagementScope(); connectScope.Path = new ManagementPath(@"\\" + machineName + path); connectScope.Options = options; connectScope.Connect(); return connectScope; }
public static ConnectionOptions ProcessConnectionOptions() { ConnectionOptions options = new ConnectionOptions(); options.Impersonation = ImpersonationLevel.Impersonate; options.Authentication = AuthenticationLevel.Default; options.EnablePrivileges = true; return options; }
private void button1_Click_1(object sender, EventArgs e) { System.Management.ConnectionOptions connOptions = new System.Management.ConnectionOptions(); connOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; connOptions.Username = "******"; connOptions.Password = "******"; string compName = "chan-PC"; System.Management.ManagementScope manScope = new System.Management.ManagementScope( String.Format(@"\\{0}\ROOT\CIMV2", compName), connOptions); manScope.Connect(); System.Management.ObjectGetOptions objectGetOptions = new System.Management.ObjectGetOptions(); System.Management.ManagementPath managementPath = new System.Management.ManagementPath("Win32_Process"); System.Management.ManagementClass processClass = new System.Management.ManagementClass(manScope, managementPath, objectGetOptions); System.Management.ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); inParams["CommandLine"] = @"c:\MalCode\hiWinForm.exe"; System.Management.ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null); var returnvalue = outParams["returnValue"]; if (outParams["returnValue"].ToString().Equals("0")) { MessageBox.Show("Process execution returned " + unchecked ((int)outParams["returnValue"])); } else { MessageBox.Show("No type specified " + unchecked ((int)outParams["returnValue"])); } }
public static DataTable WMIToDataTable(string query, string computer, string username, string password) { string qry = query; System.Management.ManagementObjectSearcher searcher; System.Management.ObjectQuery queryObj = new System.Management.ObjectQuery(qry); if (username != string.Empty && password != string.Empty && computer != string.Empty && !computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = username; oConn.Password = password; if (!computer.StartsWith(@"\\")) { computer = @"\\" + computer; } if (!computer.ToLower().EndsWith(@"\root\cimv2")) { computer += @"\root\cimv2"; } System.Management.ManagementScope oMs = new System.Management.ManagementScope(computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, queryObj); } else { searcher = new System.Management.ManagementObjectSearcher(queryObj); } System.Data.DataTable dt = new DataTable(); bool needsSchema = true; int length = 0; object[] values = null; foreach (System.Management.ManagementObject share in searcher.Get()) { if (needsSchema) { foreach (System.Management.PropertyData p in share.Properties) { System.Data.DataColumn col = new DataColumn(p.Name, ConvertCimType(p.Type)); dt.Columns.Add(col); } length = share.Properties.Count; needsSchema = false; } if (values == null) { values = new object[length]; } int x = 0; foreach (System.Management.PropertyData p in share.Properties) { if (p.Type == CimType.DateTime) { values[x] = System.Management.ManagementDateTimeConverter.ToDateTime(p.Value.ToString()); } else { values[x] = p.Value; } x++; } dt.Rows.Add(values); values = null; } return(dt); }
//method to invoke command line on remote machine public void InvokeCommand(string command) { try { //connection options var connOptions = new System.Management.ConnectionOptions(); connOptions.Authentication = AuthenticationLevel.PacketPrivacy; connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; connOptions.Username = Domain + "\\" + Username; connOptions.Password = Password; //management scope var manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", ComputerName), connOptions); manScope.Connect(); ObjectGetOptions objectGetOptions = new ObjectGetOptions(); objectGetOptions.Timeout = TimeSpan.FromSeconds(20); ManagementPath managementPath = new ManagementPath("Win32_Process"); ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions); ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); //script to execute from passed parameter inParams["CommandLine"] = command; //execute script ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null); //loop through processes until process has quit SelectQuery CheckProcess = new SelectQuery("Select * from Win32_Process Where ProcessId = " + outParams["processId"]); //counter for loop int counter = 0; int loopcounter = Convert.ToInt32(WmiTimeout) / 10; //loop until process has died while (counter != (loopcounter + 1)) { // create searcher object ManagementObjectSearcher ProcessSearcher = new ManagementObjectSearcher(manScope, CheckProcess); ProcessSearcher.Options.Timeout = TimeSpan.FromSeconds(20); // if it is not null there is a process running if (ProcessSearcher.Get().Count != 0) { if (counter == loopcounter) { // kill process inParams["CommandLine"] = "cmd /c \"taskkill /f /pid " + outParams["processId"].ToString() + " /t \""; processClass.InvokeMethod("Create", inParams, null); // throw new exception for process timeout throw new Exception("WMI process timeout"); } else { counter++; Thread.Sleep(10000); } } // if it is null then process is not running and break from loop else if (ProcessSearcher.Get().Count == 0) { break; } } } catch (Exception e) { //catch exception throw new Exception(e.Message.ToString()); } }
private void QueryButton_Click(object sender, System.EventArgs e) { AddToHistory(); this.StilRunning = true; this.QueryButton.Enabled = false; this.StopButton.Enabled = true; try { treeView1.Nodes.Clear(); if (this.QueryTextBox.Text != string.Empty) { string qry = QueryTextBox.Text; System.Management.ManagementObjectSearcher searcher; System.Management.ObjectQuery query = new System.Management.ObjectQuery(qry); if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password) && !string.IsNullOrEmpty(Computer) && !Computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = Username; oConn.Password = Password; System.Management.ManagementScope oMs = new System.Management.ManagementScope(Computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, query); } else { searcher = new System.Management.ManagementObjectSearcher(query); } System.Windows.Forms.TreeNode root = new TreeNode(qry); root.Tag = "RootNode"; root.Expand(); treeView1.Nodes.Add(root); string path = ""; foreach (System.Management.ManagementObject share in searcher.Get()) { System.Windows.Forms.TreeNode item = new TreeNode(share.ClassPath.ClassName); item.Tag = "ClassNode"; root.Nodes.Add(item); path = "Enumerating:" + share.ClassPath.ClassName; foreach (System.Management.PropertyData p in share.Properties) { bool isLocal = p.IsLocal; string type = p.Type.ToString(); string origin = p.Origin; string name = p.Name; path = "Enumerating:" + share.ClassPath.ClassName + "," + name; Application.DoEvents(); bool IsArray = p.IsArray; string val = "NULL"; if (p.Value != null) { val = p.Value.ToString(); } System.Windows.Forms.TreeNode node = new TreeNode(name); node.Tag = "PropertyNode"; string display = ""; if (type.ToLower() == "string") { display = "Value='" + val + "'"; } else { display = "Value=" + val; } System.Windows.Forms.TreeNode ValueNode = new TreeNode(display); ValueNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode TypeNode = new TreeNode("Type='" + type + "'"); TypeNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode localNode = new TreeNode("IsLocal=" + isLocal); localNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode OriginNode = new TreeNode("Origin='" + origin + "'"); OriginNode.Tag = "ValueNode"; System.Windows.Forms.TreeNode IsArrayNode = new TreeNode("IsArray=" + IsArray); IsArrayNode.Tag = "ValueNode"; node.Nodes.Add(ValueNode); node.Nodes.Add(TypeNode); node.Nodes.Add(localNode); node.Nodes.Add(OriginNode); node.Nodes.Add(IsArrayNode); if (IsArray && p.Value != null) { System.Array a = (System.Array)p.Value; for (int x = 0; x < a.Length; x++) { string v = ""; if (a.GetValue(x) != null) { v = a.GetValue(x).ToString(); } System.Windows.Forms.TreeNode arrayNode = new TreeNode(name + "[" + x + "]=" + v); arrayNode.Tag = "ArrayNode"; IsArrayNode.Nodes.Add(arrayNode); IncrementBar(); } } IncrementBar(); item.Nodes.Add(node); Application.DoEvents(); if (!this.StilRunning) { break; } } if (!this.StilRunning) { break; } } } } catch (Exception exc) { Terminals.Logging.Info("Query Button Failed", exc); MessageBox.Show("Error Thrown:" + exc.Message); } this.progressBar1.Value = 0; this.QueryButton.Enabled = true; this.StopButton.Enabled = false; }
/// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing the specified scope path, /// with the specified options.</para> /// </summary> /// <param name='path'>The server and namespace for the <see cref='System.Management.ManagementScope'/>.</param> /// <param name=' options'>A <see cref='System.Management.ConnectionOptions'/> containing options for the connection.</param> /// <example> /// <code lang='C#'>ConnectionOptions opt = new ConnectionOptions(); /// opt.Username = UserName; /// opt.Password = SecurelyStoredPassword; /// ManagementScope s = new ManagementScope("\\\\MyServer\\root\\default", opt); /// </code> /// <code lang='VB'>Dim opt As New ConnectionOptions() /// opt.Username = UserName /// opt.Password = SecurelyStoredPassword /// Dim s As New ManagementScope("\\MyServer\root\default", opt); /// </code> /// </example> public ManagementScope(string path, ConnectionOptions options) : this(new ManagementPath(path), options) { }
private void LoadServices(string Username, string Password, string Computer) { System.Text.StringBuilder sb = new StringBuilder(); string qry = "select * from win32_service"; System.Management.ManagementObjectSearcher searcher; System.Management.ObjectQuery query = new System.Management.ObjectQuery(qry); if (Username != "" && Password != "" && Computer != "" && !Computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = Username; oConn.Password = Password; if (!Computer.StartsWith(@"\\")) { Computer = @"\\" + Computer; } if (!Computer.ToLower().EndsWith(@"\root\cimv2")) { Computer = Computer + @"\root\cimv2"; } System.Management.ManagementScope oMs = new System.Management.ManagementScope(Computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, query); } else { searcher = new System.Management.ManagementObjectSearcher(query); } System.Data.DataTable dt = new DataTable(); bool needsSchema = true; int length = 0; object[] values = null; list.Clear(); foreach (System.Management.ManagementObject share in searcher.Get()) { Share s = new Share(); list.Add(share); if (needsSchema) { foreach (System.Management.PropertyData p in share.Properties) { System.Data.DataColumn col = new DataColumn(p.Name, ConvertCimType(p.Type)); dt.Columns.Add(col); } length = share.Properties.Count; needsSchema = false; } if (values == null) { values = new object[length]; } int x = 0; foreach (System.Management.PropertyData p in share.Properties) { values[x] = p.Value; x++; } dt.Rows.Add(values); values = null; } this.dataGridView1.DataSource = dt; }
private void LoadServices(string Username, string Password, string Computer) { StringBuilder sb = new StringBuilder(); string qry = "select AcceptPause, AcceptStop, Caption, CheckPoint, CreationClassName, Description, DesktopInteract, DisplayName, ErrorControl, ExitCode, InstallDate, Name, PathName, ProcessId,ServiceSpecificExitCode, ServiceType, Started, StartMode, StartName, State, Status, SystemCreationClassName, SystemName, TagId, WaitHint from win32_service"; ManagementObjectSearcher searcher; ObjectQuery query = new ObjectQuery(qry); if (Username != "" && Password != "" && Computer != "" && !Computer.StartsWith(@"\\localhost")) { System.Management.ConnectionOptions oConn = new System.Management.ConnectionOptions(); oConn.Username = Username; oConn.Password = Password; if (!Computer.StartsWith(@"\\")) { Computer = @"\\" + Computer; } if (!Computer.ToLower().EndsWith(@"\root\cimv2")) { Computer = Computer + @"\root\cimv2"; } System.Management.ManagementScope oMs = new System.Management.ManagementScope(Computer, oConn); searcher = new System.Management.ManagementObjectSearcher(oMs, query); } else { searcher = new System.Management.ManagementObjectSearcher(query); } System.Data.DataTable dt = new DataTable(); bool needsSchema = true; int length = 0; object[] values = null; list.Clear(); foreach (System.Management.ManagementObject share in searcher.Get()) { Share s = new Share(); list.Add(share); if (needsSchema) { foreach (System.Management.PropertyData p in share.Properties) { System.Data.DataColumn col = new DataColumn(p.Name, ConvertCimType(p.Type)); dt.Columns.Add(col); } length = share.Properties.Count; needsSchema = false; } if (values == null) { values = new object[length]; } int x = 0; foreach (System.Management.PropertyData p in share.Properties) { if (p != null && x < length) { values[x] = p.Value; x++; } } dt.Rows.Add(values); values = null; } this.dataGridView1.DataSource = dt; }
internal void Initialize() { //If the path is not set yet we can't do it if (null == path) { throw new InvalidOperationException(); } /* * If we're not connected yet, this is the time to do it... We lock * the state to prevent 2 threads simultaneously doing the same * connection. To avoid taking the lock unnecessarily we examine * isConnected first */ if (!IsConnected) { lock (this) { if (!IsConnected) { IWbemLocator loc = (IWbemLocator) new WbemLocator(); if (null == options) { Options = new ConnectionOptions(); } string nsPath = path.NamespacePath; // If no namespace specified, fill in the default one if ((null == nsPath) || (0 == nsPath.Length)) { // NB: we use a special method to set the namespace // path here as we do NOT want to trigger an // IdentifierChanged event as a result of this set path.SetNamespacePath(ManagementPath.DefaultPath.Path); } // If we have privileges to enable, now is the time SecurityHandler securityHandler = GetSecurityHandler(); int status = (int)ManagementStatus.NoError; try { status = loc.ConnectServer_( path.NamespacePath, options.Username, options.GetPassword(), options.Locale, options.Flags, options.Authority, options.GetContext(), out wbemServices); //Set security on services pointer Secure(wbemServices); } catch (Exception e) { // BUGBUG : securityHandler.Reset()? ManagementException.ThrowWithExtendedInfo(e); } finally { securityHandler.Reset(); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status); } } } } }