c#中可以通過wmi在遠程機上執行命令(wmi:windows management interface 可以通過一個公用的介面訪問不同作業系統(windows系統)的構成單元,利用它可以高效的管理遠程和本地的電腦。它也是w2k3,w2k8和xp的管理系統的控制核心),下面是完成這個工作的示範代碼:
//////////////////////////////////////////////////////////////////////////////////////////////////
//ConnectionOptions指定產生wmi串連所需的設定
ConnectionOptions connOption = new ConnectionOptions();
connOption.Username = domain + @"\" + userName;
connOption.Password = password;
//ManagementPath 封裝了產生和分析wmi對象的路徑
ManagementPath mngPath = new ManagementPath(@"\\" + serverHostName + @"\root\cimv2:Win32_Process");
ManagementScope scope = new ManagementScope(mngPath, connOption);
scope.Connect();
//ObjectGetOptions 類是指定用於擷取管理對象的選項
ObjectGetOptions objOption = new ObjectGetOptions();
//ManagementClass 是表示公用資訊模型 (CIM) 管理類,通過該類的成員,可以使用特定的 WMI 類別路徑訪問 WMI 資料
ManagementClass classInstance = new ManagementClass(scope, mngPath, objOption);
int ProcessId = 0;
object[] cmdline = { "cmd /c " + strCommand, path, null, ProcessId };
//調用執行命令的方法
classInstance.InvokeMethod("Create", cmdline);
其中domain是登陸遠程機的網域名稱,userName,password是登陸遠程機的帳戶密碼。
serverHostName是要訪問的遠程機名或者IP。
strCommand是需要在遠程機上面執行的命令。
//////////////////////////////////////////////////////////////////////////////////////////////////
c#中還可以通過使用 HTTP 協議傳輸訊息的用戶端通道,來實現遠程調用,下面是示範代碼:
//首先建立通道,並註冊通道服務
HttpChannel c = new HttpChannel();
ChannelServices.RegisterChannel(c, false);
//然後調用可執行檔執行操作
object remoteObject = Activator.GetObject(Type.GetType(RemoteObject), remoteObjectURL);
RemoteObject marshalObj = (RemoteObject)remoteObject;
marshalObj.RunCommand(ExeFilePath);
//關閉通道
ChannelServices.UnregisterChannel(c);
public class RemoteObject:MarshalByRefObject
{
public string RunCommand(string cmd)
{
Process p=new Process();
p.StartInfo.FileName="cmd.exe";
p.StartInfo.UseShellExecute=false;
p.StartInfo.RedirectStandardInput=true;
p.StartInfo.RedirectStandardOutput=true;
p.StartInfo.RedirectStandardError=true;
p.StartInfo.CreateNoWindow=true;
p.Start();
p.StandardInput.WriteLine(cmd);
p.StandardInput.WriteLine("exit");
p.Close();
}
}