Im am trying to get a cgi stript run by apache to command
service network restart
I just put the command in a bash file but I get a permission denied error.
#!/bin/bash
service network restart
Maybe I need a perl solution?
You could add a rule in sudoers
to let your CGI scripts run the script (and nothing else) as root. Edit sudoers
using sudo visudo
to add this line:
apache ALL = NOPASSWD: /path/to/script.sh
And then your CGI script will be able to do sudo service network restart
without entering password.
To restart system services you need administrator privileges, and I don't really think you should give Apache the rights to restart system services.
Just for the sake of answering your question, it may be enough to add the Apache user to the sudoers and modifying your script to pass the secret via stdin to the sudo
command
echo myPassword | sudo -S service network restart
An alternative may be setuid root your shell script.
But, again, this doesn't seem a good idea to me. Also note that restarting the network stack means that likely your CGI script won't be able to send a response to the client.
Only way I figured out how to do it is having the cgi script execute this to shell
ssh -i /var/www/.ssh/ssh-key root@localhost 'service network restart'
You would need to create .ssh dir with appropriate permissions in /var/www/ and ssh first from command line to add localhost to known_hosts. And obviously the ssh key should not have a password.
Another way to do this (without escalating apache's permissions or running your scripts as root) is to program your script to simply write the commands to be executed to a text file. Then, setup a daemon (or a cron job) that runs as root, scans the text file for the commands to be executed, and runs them. Just make sure the commands are safe.