在执行之前解析 STARTUPINFO hStdInput

Parsing STARTUPINFO hStdInput before executing

本文关键字:STARTUPINFO hStdInput 执行      更新时间:2023-10-16

我正在尝试使用 C++ 编写一个简单的远程 shell,并希望能够在执行命令之前解析命令,我的问题是 hStdInput 直接从 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);
可以使用

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
        } 
    }
}