C# 在远程计算机上运行命令
我想使用C#在远程计算机上的命令提示符中运行命令。根据此链接,我尝试使用以下代码执行此操作:C# 在远程计算机上运行命令,c#,wmi,command-prompt,remote-server,C#,Wmi,Command Prompt,Remote Server,我想使用C#在远程计算机上的命令提示符中运行命令。根据此链接,我尝试使用以下代码执行此操作: public static void RunRemoteCommand(string command, string RemoteMachineName) { ManagementScope WMIscope = new ManagementScope( String.Format("\\\\{0}\\root\\cimv2", RemoteMachineName));
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的退出代码,不会抛出任何错误,但不会执行任何操作。请帮助。如果您愿意尝试,这对这类事情非常有用。希望这会有所帮助
查看“备用凭证”部分。我相信你可以自己做一些小的修改。我知道这篇文章很旧,但是对于其他看到这一页的人以及完整性: 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);
}
您知道哪些
Create
方法不能用于远程启动交互式流程吗?尝试检查远程计算机的任务管理器。您将看到进程正在运行,但没有GUI。我看到了您在任务管理器中谈论的内容。有没有办法向流程中添加参数?具体地说,如果我创建了进程“cmd.exe”,是否有方法向该进程传递命令,以便它可以在远程计算机上运行?请尝试cmd.exe/c foo.exe param1 param2