我想在使用C#的远程计算机上的命令提示符下运行命令。根据此链接How to execute a command in a remote computer?,我尝试使用以下代码执行此操作:
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);
}
这将返回退出代码0并且不会抛出任何错误,但是没有执行任何操作。请帮忙。
答案 0 :(得分:1)
答案 1 :(得分:0)
如果你愿意尝试,psexec对于这类事情是很好的。
答案 2 :(得分:0)
我知道该帖子已经过时但是对于遇到此页面的其他人而言也是完整的: RRUZ的评论是正确的,但是为了在远程机器上运行,还有一件事可能需要凭证。 为此,您需要添加连接选项:
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);
}