gpt4 book ai didi

c++ - 如何在 C/C++ 程序中执行 sudo 命令?

转载 作者:行者123 更新时间:2023-11-30 17:48:30 25 4
gpt4 key购买 nike

我想通过我的 C 恶魔之一执行我的 sudo 命令之一。

我在 C 代码中使用命令 system(echo MYPASSWORD | sudo -v -S);

当我执行恶魔时它运行良好。但是,当我从终端退出时,它失败并返回值为 256。

请向我建议一些当进程在后端运行时传递密码的替代方法。

最佳答案

某些 SUDO 版本使用 open("/dev/tty") 来确保密码不能以这种方式发送。您可以执行以下操作来避免这种情况:

int ptm=open("/dev/ptmx"....);
int pid=fork();
if(!pid)
{
close(0);
close(1);
close(2);
setsid();
unlockpt(...); grantpt(...);
pts=open(ptsname...);
execl(getenv("SHELL"),"sh","-c","sudo any_command",NULL);
exit(1);
}
// now the ptm file handle is used to send data
// to the process and to receive output from the process
waitpid(...);

当所有 tty 都关闭时,调用 setsid() 并打开一个新的 tty(此处为/dev/ptsn),然后新的 tty 成为该进程的/dev/tty。这意味着:sudo将从伪终端读取密码。

编辑

我刚刚修复了示例中的一个错误:应在 fork() 之前调用 open("/dev/ptmx"...)

关于c++ - 如何在 C/C++ 程序中执行 sudo 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com