程序以root身份运行时在运行时切换用户

时间:2019-06-26 04:14:43

标签: c++ linux

如果某些c ++程序以root身份运行,而我想以不同的用户身份执行某些命令并读取该命令的输出,然后再次切换回root用户,那么有人可以指导我如何在linux OS和c ++中实现该功能?

下面是我编写的参考代码。有人可以指导我正确与否吗?

#include <iostream>
#include <stdio.h>
#include <string.h>

std::wstring PopenRead(const std::wstring &cmd)
{
    std::wstring res;
    std::string s_cmd(cmd.begin(), cmd.end());
    FILE *f = popen((const char *)s_cmd.c_str(), "r");

    if (f)
    {
            char buffer[1024];
            int cnt;
            int rc;

            while ((cnt = fread(buffer, 1, 1024, f)) > 0)
            {
                    buffer[cnt] = 0;
                    std::string s_val = std::string(buffer);
                    std::wstring wsTmp(s_val.begin(), s_val.end());
                    res += wsTmp;
            }

            rc = pclose(f);
            std::wcout << "Output is: " << res << std::endl;

            return res;
    }
    return L"";
}

int main()
{
    std::wstring command = L"su test_user -c 'ls -ltr /home/test_user'";
    std::wstring exec_res = PopenRead(command);    
    return 0;
}

1 个答案:

答案 0 :(得分:1)

我尝试使用popensudo命令来做到这一点

请在C ++中找到以下代码

Ubuntu 18.04 LTS

请使用以下命令在#include <string> #include <iostream> #include <cstdlib> #include <cstdio> #include <array> int main() { //To switch user as user std::string switch_user_command("echo 'userpassword' | sudo -u user 2>&1"); std::array<char, 128> buffer; std::string result; std::cout << "Opening reading pipe" << std::endl; FILE* pipe; pipe = popen(switch_user_command.c_str(), "r"); if (!pipe) { std::cerr << "Couldn't start command." << std::endl; return 0; } while (fgets(buffer.data(), 128, pipe) != NULL) { //std::cout << "Reading..." << std::endl; result += buffer.data(); } auto returnCode1 = pclose(pipe); std::cout << result << std::endl; std::cout << returnCode1 << std::endl; result.clear(); //To run ls command std::string command("ls 2>&1"); pipe = popen(command.c_str(), "r"); if (!pipe) { std::cerr << "Couldn't start command." << std::endl; return 0; } while (fgets(buffer.data(), 128, pipe) != NULL) { //std::cout << "Reading..." << std::endl; result += buffer.data(); } auto returnCode2 = pclose(pipe); std::cout << result << std::endl; std::cout << returnCode2 << std::endl; //To run command as root/sudo result.clear(); std::cout << "Trying to run ls as sudo .. " << std::endl; std::string switch_root_command("echo 'sudopassword' | sudo -S ls 2>&1"); pipe = popen(switch_root_command.c_str(), "r"); if (!pipe) { std::cerr << "Couldn't start command." << std::endl; return 0; } while (fgets(buffer.data(), 128, pipe) != NULL) { //std::cout << "Reading..." << std::endl; result += buffer.data(); } auto returnCode3 = pclose(pipe); std::cout << result << std::endl; std::cout << returnCode3 << std::endl; return 0; } 中进行编译

  

g ++ prog.cpp -o prog -std = c ++ 11

这将产生下面的输出(因为我没有任何“用户”帐户)

g++

希望对您有帮助!