Удалённый доступ WMI на языке C#
Формулировка задачи:
Здравствуйте, у меня такой вопрос. Как правильно реализовать удалённый доступ WMI на C#? Использовал учебник Климова - "C# советы программистам". На локальном компьютере работает, удалённо - нет. Воспользовался WMI Code Creator v1.0 с официального сайта MS - http://www.microsoft.com/en-us/download/details.aspx?id=8572
Вот код, который он мне выдал:
Для компьютера с именем FullComputerName и доменом DOMAIN. И опять не работает! Ошибка: "Отказано в доступе HRESULT:0 80070005 (E_ACCESSDENIED)". В чём проблема: нужно как-то настроить систему для WMI или всё-таки неправильный код? Буду очень благодарен за помощь в этом вопросе.
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Management; namespace WMISample { public class MyQuerySample : System.Windows.Forms.Form { private System.Windows.Forms.Label userNameLabel; private System.Windows.Forms.TextBox userNameBox; private System.Windows.Forms.TextBox passwordBox; private System.Windows.Forms.Label passwordLabel; private System.Windows.Forms.Button OKButton; private System.Windows.Forms.Button cancelButton; private System.ComponentModel.Container components = null; public MyQuerySample() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } private void InitializeComponent() { this.userNameLabel = new System.Windows.Forms.Label(); this.userNameBox = new System.Windows.Forms.TextBox(); this.passwordBox = new System.Windows.Forms.TextBox(); this.passwordLabel = new System.Windows.Forms.Label(); this.OKButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // userNameLabel // this.userNameLabel.Location = new System.Drawing.Point(16, 8); this.userNameLabel.Name = "userNameLabel"; this.userNameLabel.Size = new System.Drawing.Size(160, 32); this.userNameLabel.TabIndex = 0; this.userNameLabel.Text = "Enter the user name for the remote computer:"; // // userNameBox // this.userNameBox.Location = new System.Drawing.Point(160, 16); this.userNameBox.Name = "userNameBox"; this.userNameBox.Size = new System.Drawing.Size(192, 20); this.userNameBox.TabIndex = 1; this.userNameBox.Text = ""; // // passwordBox // this.passwordBox.Location = new System.Drawing.Point(160, 48); this.passwordBox.Name = "passwordBox"; this.passwordBox.PasswordChar = '*'; this.passwordBox.Size = new System.Drawing.Size(192, 20); this.passwordBox.TabIndex = 3; this.passwordBox.Text = ""; // // passwordLabel // this.passwordLabel.Location = new System.Drawing.Point(16, 48); this.passwordLabel.Name = "passwordLabel"; this.passwordLabel.Size = new System.Drawing.Size(160, 32); this.passwordLabel.TabIndex = 2; this.passwordLabel.Text = "Enter the password for the remote computer:"; // // OKButton // this.OKButton.Location = new System.Drawing.Point(40, 88); this.OKButton.Name = "OKButton"; this.OKButton.Size = new System.Drawing.Size(128, 23); this.OKButton.TabIndex = 4; this.OKButton.Text = "OK"; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(200, 88); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(128, 23); this.cancelButton.TabIndex = 5; this.cancelButton.Text = "Cancel"; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // MyQuerySample // this.AcceptButton = this.OKButton; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(368, 130); this.ControlBox = false; this.Controls.Add(this.cancelButton); this.Controls.Add(this.OKButton); this.Controls.Add(this.passwordBox); this.Controls.Add(this.passwordLabel); this.Controls.Add(this.userNameBox); this.Controls.Add(this.userNameLabel); this.Name = "MyQuerySample"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Remote Connection"; this.ResumeLayout(false); } [STAThread] static void Main() { Application.Run(new MyQuerySample()); } private void OKButton_Click(object sender, System.EventArgs e) { try { ConnectionOptions connection = new ConnectionOptions(); connection.Username = userNameBox.Text; connection.Password = passwordBox.Text; connection.Authority = "ntlmdomain:DOMAIN"; ManagementScope scope = new ManagementScope( "\\\\FullComputerName\\root\\CIMV2", connection); scope.Connect(); ObjectQuery query= new ObjectQuery( "SELECT * FROM Win32_Processor"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine("-----------------------------------"); Console.WriteLine("Win32_Processor instance"); Console.WriteLine("-----------------------------------"); Console.WriteLine("Name: {0}", queryObj["Name"]); } Close(); } catch(ManagementException err) { MessageBox.Show("An error occurred while querying for WMI data: " + err.Message); } catch(System.UnauthorizedAccessException unauthorizedErr) { MessageBox.Show("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message); } } private void cancelButton_Click(object sender, System.EventArgs e) { Close(); } } }
Решение задачи: «Удалённый доступ WMI на языке C#»
textual
Листинг программы
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Management; namespace CodeCreators_Remote_WMI { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } void GetCPUNameButtonClick(object sender, EventArgs e) { try { ManagementScope scope; if(localCompCheckBox.Checked) { scope = new ManagementScope("\\\\localhost\\root\\CIMV2"); } else { ConnectionOptions connection = new ConnectionOptions(); connection.Username = usernameTextBox.Text; connection.Password = passwordTextBox.Text; connection.Authority = "ntlmdomain:" + domainTextBox.Text; scope = new ManagementScope( "\\\\" + fullCompNameTextBox.Text + "\\root\\CIMV2", connection); } scope.Connect(); ObjectQuery query= new ObjectQuery("SELECT * FROM Win32_Processor"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); foreach (ManagementObject queryObj in searcher.Get()) { CPUsNameLabel.Text = "CPU's Name:\n" + queryObj["Name"].ToString(); } } catch(ManagementException err) { MessageBox.Show("An error occurred while querying for WMI data: " + err.Message); } catch(System.UnauthorizedAccessException unauthorizedErr) { MessageBox.Show("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message); } } void LocalCompCheckBoxCheckedChanged(object sender, EventArgs e) { usernameTextBox.Enabled = ! localCompCheckBox.Checked; passwordTextBox.Enabled = ! localCompCheckBox.Checked; domainTextBox.Enabled = ! localCompCheckBox.Checked; fullCompNameTextBox.Enabled = ! localCompCheckBox.Checked; } } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д