如何使用CreateProcess函数正确调用“ telnet”?

时间:2018-12-03 15:10:14

标签: winapi command-line cmd telnet createprocess

我想通过cmd.exe启动“远程登录”,并将此命令执行的结果写入文件。当我运行“ ipconfig”命令时,我会获得所需的所有信息,但是在运行“ telnet”命令后,我只会得到一个空文件。

这是我的代码:

#include "windows.h"
#include "iostream"

void SaveResult(const wchar_t *fileName, const wchar_t *commandLine)
{
    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    HANDLE h = CreateFile(fileName, FILE_WRITE_DATA, FILE_SHARE_WRITE | FILE_SHARE_READ,
        &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (h == INVALID_HANDLE_VALUE)
        return;

    PROCESS_INFORMATION pi = { 0 };
    STARTUPINFO si = { sizeof(si) };
    si.dwFlags |= STARTF_USESTDHANDLES;
    si.hStdInput = NULL;
    si.hStdError = h;
    si.hStdOutput = h;

    wchar_t *writable_cmdline = _wcsdup(commandLine);
    BOOL success = CreateProcess(NULL, writable_cmdline,
        NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);

    bool finished = false;

    //wait for 1 second
    for (int i = 0; i < 10; i++)
    {
        if (WaitForSingleObject(pi.hProcess, 100) <= 0)
        {
            finished = true;
            break;
        }
    }

    if (success)
    {
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }

    CloseHandle(h);
    free(writable_cmdline);

    if (!finished)
        printf("Process didn't finish\n");
}


int main()
{
    SaveResult(L"telnet.txt", L"C:\\windows\\system32\\cmd.exe /c telnet test.com");
    SaveResult(L"ipconfig.txt", L"C:\\windows\\system32\\cmd.exe /c ipconfig");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您是否直接在cmd控制台中运行telnet命令?有什么输出吗?如果是这样,则空文件可能是因为缓冲区尚未刷新到该文件。正如@David指出的那样, 您只需等待1s,但是如果连接的时间超过1s,则将关闭处理程序而不刷新缓冲区。尝试在FlushFileBuffers(h)之前添加CloseHandle(h)。 对于WaitForSingleObject,您可以尝试WaitForSingleObject(pi.hProcess, INFINITE),等到telnet进程退出。