Skip to content
Advertisement

How to execute a sudo command with in a C/C++ Program?

I would like to execute one of my sudo commands 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. However, when I exit from the terminal it fails with a return value of 256.

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement