Reputation: 33
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.
Upvotes: 2
Views: 15609
Reputation: 18523
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()
.
Upvotes: 2
Reputation: 2568
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
Upvotes: 0