如果某个 C++ 程序以 root 身份运行,并且我想使用不同的用户执行一些命令并读取该命令的输出,然后再次切换回 root 用户,那么有人可以指导我如何在 Linux 操作系统和 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;
}
最佳答案
我尝试使用 popen
和 sudo
命令来执行此操作,因为我使用的是 Ubuntu 18.04 LTS
请找到以下 C++ 代码
#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++
中编译
g++ prog.cpp -o prog -std=c++11
这会产生以下输出(因为我没有任何“用户”帐户)
Opening reading pipe
sudo: unknown user: user
sudo: unable to initialize policy plugin
256
1.cpp
2
2.cpp
0
Trying to run ls as sudo ..
1.cpp
2
2.cpp
0
abhi
0
希望对您有帮助!
关于c++ - 当程序以 root 身份运行时,在运行时切换用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56765083/