Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute sudo command in C with system()

Tags:

c

sudo

root

I am writing a piece of C code that will run some sudo command in system("sudo ip route ...") function call.

This call is being done in a pthread created by the main thread, and the main program is being executed with sudo ./program when starting up.

When I run the program, Ubuntu prompts me to enter password for nobody:

[sudo] password for nobody:

I also tried to do system("ip route ...") straightly but it gives me negative return meaning that it is not executed.

What should I do in the thread to allow the system()call to use the sudo privilege inherited from the main program?

like image 316
Lingyuan He Avatar asked Apr 04 '15 01:04

Lingyuan He


People also ask

Can I run sudo in a script?

Sometimes, we would like to allow all users with sudo privilege to run a program as root without asking for passwords. Now, all users with sudo privilege can run the script /tmp/test/cpvimrc.sh as the superuser without providing passwords.

What is sudo command in CMD?

If you prefix “sudo” with any command, it will run that command with elevated privileges or in other words allow a user with proper permissions to execute a command as another user, such as the superuser. This is the equivalent of “run as administrator” option in Windows.

What commands can you run with sudo?

The sudo command allows you to run programs with the security privileges of another user (by default, as the superuser). It prompts you for your personal password and confirms your request to execute a command by checking a file, called sudoers , which the system administrator configures.


2 Answers

You don't need to do anything special to inherit the root privileges that sudo has given you. Processes generally automatically inherit the privileges of their parents. The reason system(3) isn't working is probably either because you're root (see below) or because you're on a thread.

That being said, don't use system(3). This is because sudo works by using setuid, and that doesn't play well with system(). Therefore, use the exec(3) family of functions instead (except for execlp() and execvp()). See man 3 system for more information.

Now, with that being said, don't use system(3) or exec(3). Instead, just directly call the C API for manipulating the IP tables. Why would you waste system resources spawning a new process or two, when you could just simplify your program instead? (At this point you're getting to the point where your question belongs on Stack Overflow, though).

like image 85
strugee Avatar answered Sep 24 '22 11:09

strugee


system("echo XXXX | sudo -S gedit");

Where XXXX your password.

like image 37
firebitsbr Avatar answered Sep 22 '22 11:09

firebitsbr