PsExec在远程计算机中运行批处理文件

时间:2015-04-30 16:01:50

标签: batch-file c++builder remote-server psexec

我使用此代码C ++构建器在远程计算机中执行批处理文件

String PsExec = ExtractFilePath(Application->ExeName) + "PSTools\\PsExec.exe";
String lcParam = " \\"+gl_HostName+" cmd /c  "+TDirectory::GetParent(rootPath)+"\\...\\File1.bat "+IntToStr(8988) ;

SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = PsExec.c_str();
ShExecInfo.lpParameters = lcParam.c_str();
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_NORMAL;//SW_HIDE ;
ShExecInfo.hInstApp = NULL;

ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
bool res = ShellExecuteEx(&ShExecInfo); // Call to function
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);

它不起作用!

但是,当我将cmd运行到控制台时:

\PSTools> PsExec.exe \\x.y.z.w \\x.y.z.w\.....\File1.bat 8988

它可以正常工作并在远程计算机上运行此批处理!

我的示例代码有什么问题?

1 个答案:

答案 0 :(得分:1)

正如亚历克斯所说,你没有在你的主机名中提供足够的斜杠。您只提供1个转义斜杠,但您需要2个:

String lcParam = _D(" \\\\") + gl_HostName + _D(" cmd /c ") + TDirectory::GetParent(rootPath) + _D("\\...\\File1.bat ") + IntToStr(8988);

话虽如此,您还应该使用CreateProcess()代替ShellExecuteEx()来运行.exe文件:

String PsExec = ExtractFilePath(Application->ExeName) + _D("PSTools\\PsExec.exe");
String lcParam = _D(" \\\\") + gl_HostName + _D(" cmd /c ") + TDirectory::GetParent(rootPath) + _D("\\...\\File1.bat ") + IntToStr(8988);
String CmdLine = AnsiQuotedStr(PsExec, _D('\"')) + _D(" ") + lcParam;

STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_NORMAL;

PROCESS_INFORMATION pi = {0};

if (CreateProcessW(NULL, CmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    CloseHandle(pi.hThread);
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
}