Skip to content

Instantly share code, notes, and snippets.

@justaguywhocodes
Created October 24, 2024 15:24
Show Gist options
  • Save justaguywhocodes/e615e88f9ec80025ce427751553161ee to your computer and use it in GitHub Desktop.
Save justaguywhocodes/e615e88f9ec80025ce427751553161ee to your computer and use it in GitHub Desktop.
#include <windows.h>
#include <stdio.h>
void RunWhoamiAndSaveOutput() {
SECURITY_ATTRIBUTES sa;
HANDLE hRead, hWrite;
STARTUPINFO si;
PROCESS_INFORMATION pi;
CHAR buffer[4096];
DWORD bytesRead;
BOOL bSuccess;
// Step 1: Set up security attributes
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
// Step 2: Create a pipe for the child process's STDOUT
if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
// Handle the error.
return;
}
// Ensure the read handle to the pipe is not inherited
SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
// Step 3: Set up the STARTUPINFO structure
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.dwFlags |= STARTF_USESTDHANDLES;
// Step 4: Create the child process
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
TCHAR cmdLine[] = TEXT("whoami");
bSuccess = CreateProcess(
NULL,
cmdLine,
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&si,
&pi
);
// Step 5: Close the write end of the pipe
CloseHandle(hWrite);
if (!bSuccess) {
// Handle the error.
CloseHandle(hRead);
return;
}
// Step 6: Read the output from the child process
FILE *outputFile = fopen("output.txt", "w");
if (!outputFile) {
// Handle the error.
CloseHandle(hRead);
return;
}
while (TRUE) {
bSuccess = ReadFile(hRead, buffer, sizeof(buffer) - 1, &bytesRead, NULL);
if (!bSuccess || bytesRead == 0) break;
buffer[bytesRead] = '\0';
fputs(buffer, outputFile);
}
fclose(outputFile);
// Step 7: Clean up
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(hRead);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment