C#远程调用方法

来源:互联网 发布:js获取日期加一天 编辑:程序博客网 时间:2024/06/03 15:53

       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();

                }
            }

原创粉丝点击