Run command on remote computer

巧了我就是萌 提交于 2019-12-22 12:41:10

问题


I want to run a command in command prompt on a remote computer using C#. Per this link How to execute a command in a remote computer?, I am trying to do this using the following code:

public static void RunRemoteCommand(string command, string RemoteMachineName)
{
    ManagementScope WMIscope = new ManagementScope(
        String.Format("\\\\{0}\\root\\cimv2", RemoteMachineName));
    WMIscope.Connect();
    ManagementClass WMIprocess = new ManagementClass(
        WMIscope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
    object[] process = { command };
    object result = WMIprocess.InvokeMethod("Create", process);
    Log.Comment("Creation of process returned: " + result);
}

This returns an exit code of 0 and no errors are thrown, yet nothing is executed. Please help.


回答1:


Hope this will help

http://www.petri.co.il/command-line-wmi-part-2.htm

Have a look into "Alternate Credentials" section. i believe you are able to do the little modification yourself.




回答2:


If you are willing to try it out, psexec is great for this sort of thing.




回答3:


I know the post is old but for others who come across this page and also completeness: RRUZ's comment is correct , but there is also one more thing you might need in order to run on the remote machine, credentials. To do that you need to add connection options:

public static void RunRemoteCommand(string command, string RemoteMachineName, 
                                    string username,string password)
{


            var connection = new ConnectionOptions();
            connection.Username = username;
            connection.Password = password;


    ManagementScope WMIscope = new ManagementScope(
        String.Format("\\\\{0}\\root\\cimv2", RemoteMachineName), connection);
    WMIscope.Connect();
    ManagementClass WMIprocess = new ManagementClass(
        WMIscope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
    object[] process = { command };
    object result = WMIprocess.InvokeMethod("Create", process);
    Log.Comment("Creation of process returned: " + result);
}


来源:https://stackoverflow.com/questions/17099074/run-command-on-remote-computer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!