匿名管道读取CMD回显信息

最近改exp的时候用到的,加到exp里面回显执行信息,保存一份~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <windows.h>
#include <stdio.h>
#define EXE_NAME NULL//TEXT("Cmd.exe")
#define EXE_CMD TEXT("Cmd.exe /C ipconfig/all")
int main()
{

char Buffer[4096];
STARTUPINFO sInfo;//新进程的主窗口特性
PROCESS_INFORMATION pInfo;
SECURITY_ATTRIBUTES sa;
HANDLE hRead, hWrite;
DWORD bytesRead; //读取代码的长度
sa.nLength = sizeof(SECURITY_ATTRIBUTES); //结构体的大小,可用SIZEOF取得
sa.lpSecurityDescriptor = NULL;//安全描述符
sa.bInheritHandle = TRUE; //安全描述的对象能否被新创建的进程继承

if (!CreatePipe(&hRead, &hWrite, &sa, 0)) //创建匿名管道
{
return GetLastError(); //返回最近的一个错误,0表示正常
}

GetStartupInfo(&sInfo);
sInfo.cb = sizeof(sInfo);
sInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
sInfo.wShowWindow = SW_HIDE;
sInfo.hStdError = hWrite; //将管道的写端交给子进程
sInfo.hStdOutput = hWrite;
memset(&pInfo, 0, sizeof(pInfo));

if (!CreateProcess(EXE_NAME, EXE_CMD, NULL, NULL, TRUE, 0, NULL, NULL, &sInfo, &pInfo)) //创建子进程
{
CloseHandle(hWrite);
CloseHandle(hRead);
return GetLastError();
}
CloseHandle(hWrite); //关闭父进程的写端


for (int i = 0;; ++i)
{
if (!ReadFile(hRead, Buffer, sizeof(Buffer) - 1, &bytesRead, NULL)) //读取内容
{
break;
}
Buffer[bytesRead] = 0;
printf("%s\n", Buffer);

}

WaitForSingleObject(pInfo.hProcess, INFINITE);//当等待仍在挂起状态时,句柄被关闭,那么函数行为是未定义的。该句柄必须具有 SYNCHRONIZE 访问权限;
CloseHandle(hRead);
system("pause");
return 0;
}

from: http://www.cnblogs.com/onlyac/p/5346478.html

------本文结束,感谢阅读------