简体   繁体   English

在远程计算机上运行命令

[英]Run command on remote computer

I want to run a command in command prompt on a remote computer using C#. 我想使用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. 这将返回退出代码0,并且不会引发任何错误,但是什么也不执行。 Please help. 请帮忙。

Hope this will help 希望这会有所帮助

http://www.petri.co.il/command-line-wmi-part-2.htm 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. 我相信您可以自己进行一些修改。

如果您愿意尝试一下, psexec非常适合此类事情。

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. 我知道该帖子很旧,但对于浏览该页面的其他人也是如此:RRUZ的评论是正确的,但要在远程计算机上运行,​​可能还需要另外一件事,即凭据。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM