简体   繁体   中英

execute a sudo command with in a C/C++ Program

I would like to execute one of my sudo command through one of my C demon.

I use the command system(echo MYPASSWORD | sudo -v -S); in my C code.

It runs fine when I execute the demon, But when I exit from the terminal it fails with a return value of 256.

Please suggest me some alternate way to pass the password when the process is running in backend.

Some SUDO versions use open("/dev/tty") to ensure that the password cannot be sent this way. You could do the following to avoid this:

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(...);

When all ttys are closed, setsid() is called and a new tty is opened (here the /dev/ptsn) then the new tty becomes the /dev/tty for the process. This means: sudo will read the password from the pseudo-terminal.

EDIT

I just fixed a bug in my example: open("/dev/ptmx" ...) should be called before fork() .

Another option is to execute sudo commands without a password. To do that you can open the file /etc/sudoers with your favourite editor and add this line at the end. Remember to change the yourname with the user name.

yourname ALL = (ALL) NOPASSWD: ALL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM