你的位置:首页 > ASP.net教程

[ASP.net教程]C#实现远程机器管理

     目前处于待离职状态,原先所有的工作都在进行交接,过程当中不乏有很多先前整理的和动手尝试实现的功能;我的主页中已经列出来一部分内容,有兴趣的可以前往看一看。     

     接下来的内容主要介绍另外一个工具,用于对远程主机进行远程控制、进程管理、服务管理以及WMI相关信息显示等;其中仍然存在部分问题还没有得到有效的解决,希望曾经参与过或者有关相关经验的前辈能够指导一下。

一、很搓很搓的主界面

1、配置菜单里面包括远程主机连接配置信息的添加和编辑,界面如下:


1、远程控制功能

     工具内实现的远程控制功能需要引用AxInterop.MSTSCLib.dll和Interop.MSTSCLib.dll文件,具体代码如下:


  public partial class DesktopForm : Form, IRemote  {    private AxMsRdpClient4 rdpc = null;    public RemoteMachine Machine { get; set; }    public DesktopForm(RemoteMachine machine)    {      InitializeComponent();      Text = string.Format("【远程】{0}", machine.DesktopName);      this.Machine = machine;    }    private void DesktopForm_Load(object sender, EventArgs e)    {      this.rdpc = new AxMsRdpClient4() { Dock = DockStyle.Fill };      this.rdpc.OnDisconnected += rdpc_OnDisconnected;      this.Controls.Add(this.rdpc);      this.SetRdpClientProperties(this.Machine);      Connect();    }    private void rdpc_OnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)    {    }    public bool Connect()    {      try      {        rdpc.Connect();        return true;      }      catch (Exception ex)      {        MessageBox.Show(ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);        return false;      }    }    public void Disconnect()    {      try      {        if (rdpc.Connected == 1)          rdpc.Disconnect();      }      catch (Exception ex)      {        MessageBox.Show(ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);      }    }    private void SetRdpClientProperties(RemoteMachine machine)    {      rdpc.Server = machine.Server;      rdpc.UserName = machine.UserName;      rdpc.Domain = machine.Domain;      if (!string.IsNullOrEmpty(machine.Password))        rdpc.AdvancedSettings5.ClearTextPassword = machine.Password;      rdpc.AdvancedSettings5.RedirectDrives = machine.RedirectDrives;      rdpc.AdvancedSettings5.RedirectPrinters = machine.RedirectPrinters;      rdpc.AdvancedSettings5.RedirectPorts = machine.RedirectPorts;      rdpc.ColorDepth = (int)machine.ColorDepth;      rdpc.Dock = DockStyle.Fill;    }  }

通过使用RemoteMachine参数实例化并进行远程控制;

          RemoteMachine mac = item.Tag as RemoteMachine;          using (DesktopForm df = new DesktopForm(mac))          {            df.ShowDialog();          }

 2、进程、服务管理等(WMI方式,需要引人System.Management.dll类库,以进程管理为例,ProcessInfo类包含的属性信息可查询MSDN,其他类似)

  public partial class ProcessForm : Form, IRemote  {    private ManagementScope scope = null;    private ManagementClass managementClass = null;    private string path = null;    public RemoteMachine Machine { get; set; }    public ProcessForm(RemoteMachine machine)    {      InitializeComponent();      Text = string.Format("【进程】{0}", machine.DesktopName);      this.Machine = machine;      this.path = "\\\\" + this.Machine.Server + "\\root\\cimv2:Win32_Process";      this.managementClass = new ManagementClass(this.path);      ConnectionOptions options = null;      if (this.Machine.Server != "." && this.Machine.UserName != null && this.Machine.UserName.Length > 0)      {        options = new ConnectionOptions();        options.Username = this.Machine.UserName;        options.Password = this.Machine.Password;        //options.EnablePrivileges = true;        //options.Impersonation = ImpersonationLevel.Impersonate;        //options.Authority = "ntlmdomain:domain";       }      this.scope = new ManagementScope("\\\\" + this.Machine.Server + "\\root\\cimv2", options);      this.managementClass.Scope = this.scope;    }    private DataGridView dataGrid;    private ContextMenuStrip contextMenu;    private ProcessInfo[] processes;    private void ProcessForm_Load(object sender, EventArgs e)    {      this.contextMenu = new ContextMenuStrip();      ToolStripItem item = this.contextMenu.Items.Add("停止");      item.Click += item_Click;      this.dataGrid = new DataGridView() { Dock = DockStyle.Fill, ContextMenuStrip = this.contextMenu, SelectionMode = DataGridViewSelectionMode.FullRowSelect, AllowUserToAddRows = false, AllowUserToDeleteRows = false, ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize, ReadOnly = true, RowHeadersWidth = 21 };      this.Controls.Add(this.dataGrid);      ReLoad();    }    private void ReLoad()    {      this.dataGrid.DataSource = null;      this.processes = null;      if (Connect())      {        processes = GetProcess();        DataTable table = ProcessInfo.ConvertTo(processes);        BindData(table);      }    }    private void item_Click(object sender, EventArgs e)    {      if (this.dataGrid.SelectedRows.Count == 1)      {        try        {          UInt32 processId = Convert.ToUInt32(this.dataGrid.SelectedRows[0].Cells[0].Value);          string processName = this.dataGrid.SelectedRows[0].Cells[1].Value.ToString();          if (processName != null && MessageBox.Show(string.Format("是否停止\"{0}\"进程?", processName), "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)          {            ProcessInfo process = Array.Find(processes, (pro) => { return pro.Name == processName && pro.ProcessId == processId; });            KillProcess(process);            ReLoad();          }        }        catch (Exception ex)        {          MessageBox.Show(ex.Message, "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);        }      }    }    public bool Connect()    {      try      {        scope.Connect();      }      catch (Exception ex)      {        MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);      }      return scope.IsConnected;    }    public void Disconnect()    {    }    public void BindData(DataTable table)    {      this.dataGrid.DataSource = table;    }    public ProcessInfo[] GetProcess()    {      ManagementObjectCollection queryCollection = this.managementClass.GetInstances();      List<ProcessInfo> processes = new List<ProcessInfo>();      foreach (ManagementObject m in queryCollection)      {        ProcessInfo process = new ProcessInfo(m);        processes.Add(process);      }      return processes.ToArray();    }    public void KillProcess(ProcessInfo process)    {      ObjectQuery query = new ObjectQuery(string.Format("select * from Win32_Process where ProcessId={0}", process.ProcessId));      ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);      ManagementObjectCollection queryCollection = searcher.Get();      foreach (ManagementObject m in queryCollection)      {        string[] args = new string[] { "0" };        object obj = m.InvokeMethod("Terminate", args);        Console.WriteLine(obj.ToString());        return;      }    }  }

可以通过KillProcess来终止进程;

三、所遇到的问题

(未完待续...)

此处附上源码