执行前解析STARTUPINFO hStdInput

时间:2019-01-07 09:59:16

标签: c++ sockets winapi

我正在尝试使用C ++编写一个简单的远程Shell,并且希望能够在执行命令之前对其进行解析,我的问题是hStdInput直接从WSASocket句柄获取输入,因此它会自动在WSASocket句柄上执行命令远程计算机,是否有一种方法可以解析hStdInput并采取相应的措施?或以另一种方式做?

这是一个代码段:

sinfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);
sinfo.hStdInput = sinfo.hStdOutput = sinfo.hStdError = (HANDLE)mySocket;
CreateProcess(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo, &pinfo);
WaitForSingleObject(pinfo.hProcess, INFINITE);
CloseHandle(pinfo.hProcess);
CloseHandle(pinfo.hThread);

1 个答案:

答案 0 :(得分:1)

您可以使用CreatePipe创建连接到子进程的匿名管道,而不是直接将套接字连接到子进程。

HANDLE read_pipe, write_pipe;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
CreatePipe(&read_pipe, &write_pipe, &sa, 0);

sinfo.hStdInput = read_pipe;
sinfo.hStdOutput = sinfo.hStdError = (HANDLE)mySocket;

CreateProcess(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo, &pinfo);
HANDLE handles[2] = {pinfo.hProcess, mySocket};

char buffer[1024];
while(true) {
    DWORD wfmo = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
    if(wfmo == WAIT_OBJECT_0) {
        // process died
        break;
    } else if(wfmo == WAIT_OBJECT_0+1) {
        // read socket and write to write_pipe
        DWORD NumberOfBytesRead;
        DWORD NumberOfBytesWritten;
        if(ReadFile(mySocket, buffer, 1024, &NumberOfBytesRead, NULL)) {
            char* bptr = buffer;
            while(NumberOfBytesRead) {
                if(WriteFile(write_pipe, bptr, NumberOfBytesRead, &NumberOfBytesWritten, NULL)) {
                    bptr += NumberOfBytesWritten;
                    NumberOfBytesRead -= NumberOfBytesWritten;
                } else {
                    // write failed
                }
            }
        } else {
            // read failed
        } 
    }
}