尝试通过cmd shell在远程计算机上启动exe或bat文件

问题描述 投票:0回答:2

从命令行运行以下命令以在远程计算机上启动进程

 wmic /node:remotemachine /user:localadmin process call create "cmd.exe /c C:\temp\myfolder\test.bat"

基本上就是这样

 echo Some Text > output.txt

我通过双击批处理文件进行测试,然后创建output.txt文件。

批处理文件只是回显到一个文件。我这样做是为了看它是否真的运行。

cmd进程开始。我可以在进程中看到它,但批处理文件从不创建文本文件。

我开始尝试从我的C#应用​​程序运行EXE,但它将为可执行文件创建进程,但是可执行文件所执行的操作永远不会发生。

所以我开始测试其他方法来做同样的事情,我遇到了同样的问题。它创建了进程,但实际上并没有运行bat或exe。

任何帮助,将不胜感激。

我需要更具体

我在我的C#应用​​程序中使用以下代码:

public static void ConnectToRemoteClient(string client_machine, string target_exe )
{
    var connection = new ConnectionOptions();
    object[] theProcessToRun = { target_exe };

    var wmiScope = new ManagementScope($@"\\{client_machine}\root\cimv2", connection);

    wmiScope.Connect();

    using (var managementClass = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()))
    {
        managementClass.InvokeMethod("Create", theProcessToRun );
    }   
}

它被称为如下:

使用以下语法调用它:

string exe = string.Format(@"cmd.exe /c C:\temp\Myfolder\test.bat");
ConnectToRemoteClient("ClientMachine", exe);

它将启动该进程,我看到cmd.exe正在运行,但test.bat操作永远不会发生。

wmi remote-access wmic
2个回答
1
投票

告诉WMIC运行单个命令非常简单。一旦我们尝试将一个命令嵌套在另一个命令中,就会出现问:-)

由于这种情况有一个外部命令(cmd.exe)和一个内部命令(C:\ temp \ Myfolder \ test.bat),诀窍是以WMIC可以使用的方式分离它们。有3种技术可以使用,但是具有特殊字符问题最少的技术是单对双重包装方法。实际上,您可以在外部命令周围使用单引号,并在内部命令周围使用双引号。例如:

wmic /node:NameOfRemoteSystem process call create 'cmd.exe /c "whoami /all >c:\temp\z.txt"'

以这种方式包装将保留重定向器(>),并且它也不需要您在内部命令上加倍反斜杠。

示例输出:

dir \\NameOfRemoteSystem\c$\temp\z.txt
File Not Found

wmic /node:NameOfRemoteSystem process call create 'cmd.exe /c "whoami /all >c:\temp\z.txt"'
Executing (Win32_Process)->Create()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
        ProcessId = 20460;
        ReturnValue = 0;
};

dir \\NameOfRemoteSystem\c$\temp\z.txt
03/27/2019  04:40 PM            17,977 z.txt

0
投票

请使用下面提到的powershell命令

Invoke-Command -ComputerName  <remoteMachine> -Credential $cred -ScriptBlock {<location of batch file>}
© www.soinside.com 2019 - 2024. All rights reserved.