How to run a file with sudo without a password? [duplicate]
Solution 1:
Use visudo
for a safe editing environment to edit the sudoers file. This script is a wrapper around vi
that also does syntax checking when you save the file and won't let you overwrite a valid sudoers file with an invalid one.
Add a line like this:
username ALL= NOPASSWD: /path/to/your/script
The "ALL=" bears some elaboration, it specifies that the permission is granted when the user in question is logged in from any location, locally (console or terminal) or remotely (ssh, etc).
Solution 2:
For completeness sake, you can achieve a similar effect by setting setuid bit in the file's permissions.
A slightly tricky part is that for security reasons setuid
bit on scripts is ignored by the kernel, so you'll need to compile a small wrapper program in C and use it to invoke your script. Save this as runscript.c
:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
setuid( 0 );
system( "/path/to/script.sh" );
return 0;
}
then compile it with
gcc runscript.c -o runscript
and set setuid
bit on the executable:
sudo chown root:root runscript
sudo chmod 4755 runscript
It is also important to make sure your script is only writable by root, since everyone who can modify the script will be able to execute arbitrary programs:
sudo chown root:root /path/to/script.sh
sudo chmod 0711 /path/to/script.sh
Here's an article I've got the wrapper program code from: setuid on shell scripts.
Security-wise, both approaches - the one with sudo
and the one with setuid
- are pretty bad, but probably will be ok on a home machine. The difference is that every user in the system will be able to run a setuid
command, even without being in the sudoers
file. Also, obviously, you won't need to prefix the command with sudo
.