最近在学习Windows远程CMD 遇到一些问题
代码如下:
#include <windows.h>
#include <cstdio>
void ShowError(const char* szText)
{
char szError[MAX_PATH] = { 0 };
sprintf_s(szError, "%s: %d\n", szText, GetLastError());
printf("%s", szError);
}
BOOL PipeCmd(char *szCmdLine, char *szResBuff, DWORD dwResBuffSize)
{
BOOL bRet = FALSE;
HANDLE hReadPipe = NULL;
HANDLE hWritePipe = NULL;
SECURITY_ATTRIBUTES SecAttributes = { 0 };
SecAttributes.bInheritHandle = TRUE;
SecAttributes.lpSecurityDescriptor = NULL;
SecAttributes.nLength = sizeof(SecAttributes);
bRet = CreatePipe(&hReadPipe, &hWritePipe, &SecAttributes, 0);
if (FALSE == bRet)
{
ShowError("CreatePipe");
return FALSE;
}
STARTUPINFO si = { 0 };
GetStartupInfo(&si);
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
PROCESS_INFORMATION pi = { 0 };
bRet = CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (FALSE == bRet)
{
ShowError("CreateProcess");
return FALSE;
}
RtlZeroMemory(szResBuff, dwResBuffSize);
DWORD dwRes;
ReadFile(hReadPipe, szResBuff, dwResBuffSize, &dwRes, NULL);
WaitForSingleObject(pi.hThread, INFINITE);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return TRUE;
}
int main(int argc, char *argv[])
{
char szCmdLine[] = "whoami";
char szResBuff[1024] = { 0 };
DWORD dwResBuffSize = 1024;
if (!PipeCmd(szCmdLine, szResBuff, dwResBuffSize))
{
printf("Pipe CMD ERROR\n");
}
else
{
printf("Pipe CMD OK\n");
printf("%s\n", szResBuff);
}
return 0;
}
这段程序的目的是执行命令行命令 并且将输出结果写入管道
将管道数据读入数组 最终打印出数组
简而言之就是用程序执行CMD命令并且输出返回结果
但执行程序后得不到任何输出