티스토리 뷰

IT/C, C++

콘솔창에 명령어를 실행하여 출력된 값 받아오기

주인장 진빼이

windows, linux 모두 사용 가능하다

특정 명령어에 대한 pipe를 이용하여 출력된 문자열을 버퍼에 담아 출력하는 것이다.

certutil -hashfile <path> 명령어를 사용하여 파일 해시값을 구할 수 있다.

// Windows OS
#include "pch.h"
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

std::string exec(const char* cmd)
{
	char buffer[128];
	std::string result = "";
	FILE* pipe = _popen(cmd, "r");
	static int i = 1;
	if (!pipe) throw std::runtime_error("popen() failed!");
	try
	{
		while (fgets(buffer, sizeof buffer, pipe) != NULL)
        {
			if (i++ == 2)
			{
				result += buffer;
			}
			std::cout << (i) << "buffer" << buffer;
		}
	}
	catch (...)
	{
		_pclose(pipe);
		throw;
	}
	_pclose(pipe);
	return result;
}

int main()
{
	std::string s = exec("certutil -hashfile C:\\Windows\\notepad.exe");
	std::cout << "res: " << s;
}


//Unix (macOS)
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

std::string exec(const char* cmd)
{
	char buffer[128];
	std::string result = "";
	FILE* pipe = popen(cmd, "r");
	static int i = 1;
	if (!pipe) throw std::runtime_error("popen() failed!");
	try {
		while (fgets(buffer, sizeof buffer, pipe) != NULL)
        {
            result += buffer;
			std::cout << (i) << "buffer" << buffer;
		}
	}
	catch (...) {
		pclose(pipe);
		throw;
	}
	pclose(pipe);
	return result;
}

int main()
{
    std::string command;
    std::cin >> command;
	std::string s = exec("ls -la");
	std::cout << "res: " << s;
}

 

아쉽게도 certutil 프로세스를 실행하는 것이기에 프로세스 생성에 대한 오버헤드가 존재한다.

오버헤드가 적은 것을 원한다면 openssl, wincrypt api를 이용하자

 

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함