如何在linux上从c++程序将权限级别提升到root
How to elevate privilege level to root from c++ program on linux
我想从C++代码更改我的默认网关。我使用eclipse作为IDE。以下是我的代码。
//change_gw.cpp
#include <iostream>
#include <unistd.h>
using namespace std;
//To execute terminal commands
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main() {
int euid = geteuid();
int uid = getuid();
cout<<"euid is "<<euid<<endl;
cout<<"uid is "<<uid<<endl;
int result = setreuid(euid,-1); //change the uid to euid (0 - root)
if(result != 0) {
cout<<strerror(errno)<<endl;
return -1;
}
string result = exec("sudo route del default");
if (result == "ERROR") {
cout<<"del route failed"<<endl;
return -1;
}
result = exec("sudo route add default gw ip dev iface");
if (result == "ERROR") {
cout<<"add route failed"<<endl;
return -1;
}
cout<<"route changed succefully"<<endl;
setreuid(uid,-1); //revert the changes to uid
return 0;
}
我已经成功地编译了这段代码并获得了可执行文件。编译是在eclipse环境中完成的。我从终端手动对可执行文件进行了以下更改。
chown root:root change_gw //change the owner to root
chmod u+s change_gw //set user id
现在,当我从eclipse环境中运行可执行文件时,我会得到以下输出。
euid = 0
uid = 1002
route changed successfully
虽然上面的代码运行良好,但我想知道我所做的方式是否正确有效。由于编译是在eclipse环境中完成的,可执行文件的用户每次都会从root用户更改为本地用户,我每次都需要更改setuserid标志。我怎么能避免每次都做这种改变呢?
不需要setreuid()
调用。可执行文件上的suid位就足够了,并且可以做完全相同的事情。这个setreuid()
调用在这里什么都不做。
如果需要执行setgid()
或setuid()
,则可能需要也可能不需要执行。
相关文章:
- Termux权限被拒绝
- AWS Lambda C++运行时权限被拒绝
- 如何将分支添加到已存在的TTree:ROOT
- 为什么 KMS drmModeSetCrtc() 在 X11 会话中运行时会失败并被拒绝权限?
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 在没有管理员权限的情况下连接到同一网络中的命名管道
- 为什么我在空指针错误(链表)中获取成员访问权限
- 链接 boost 库时"Error while loading shared libraries"引发的,除了我无法使用 root 访问权限来修复它
- 在没有root权限的情况下安装NTL,并在生成文件中修改其构建路径
- 如何在不需要 root 访问权限的情况下为应用程序中的线程设置相对线程优先级
- 创建具有root访问权限的CLI应用程序
- 如何访问 "askpass" 程序以在 GUI 中获取 root 权限?
- 如何在没有root权限的情况下在Linux中读取HD串行
- 如何在Qt程序内获得root权限
- 如何以编程方式启动程序并在 Linux 上使用 root 权限运行它
- 以root权限调用c++函数,而不以root身份执行整个程序
- 如何在linux上从c++程序将权限级别提升到root
- 我需要root权限才能在Android下执行本机应用程序
- linux服务器上的C++11兼容编译器,无需root访问权限
- 在基于HPC的远程Linux上切换gcc版本(没有root权限)