In a previous post I explained a possible way to shutdown a server with a php page. (here)
Now I will provide a more efficient way using a cgi-script.
Pre-requisites for apache
In order for the code to work you'll have to make sure that the correct modules are loaded. We need the following to modules:
LoadModule cgi_module /usr/lib/apache2/modules/mod_cgi.so LoadModule alias_module /usr/lib/apache2/modules/mod_alias.so LoadModule suexec_module /usr/lib/apache2/modules/mod_suexec.so
When that is done we need to add a directory where we want to place our shutdown-script. e.g. /var/www/bin
ScriptAlias /bin/ /var/www/bin/
We also need to define a user with whom we want to execute the script. This must not be a system user (i.e. it must be possible to login as the user account and uid must be greater then 500.)
SuexecUserGroup username groupname
This will be all for the Apache configuration.
The script
First we create the directory and we make sure that the directory is owned by the same user as whom is going to execute the script.
sudo mkdir /var/www/bin sudo chown username.groupname /var/www/bin
Within the script we just call the shutdown command. So create a script /var/www/bin/shutdown.cgi with contents:
#!/bin/bash echo -e "Content-type: text/html\n" # ^ Necessary HTTP header, needs to be finished with an empty line sudo /sbin/shutdown -h now
Give the script execute permissions:
chmod +x /var/www/bin/shutdown.cgi
Sudo without a password
If you were paying attention when reading the previous script you have noticed that we used sudo. The first time you use sudo you will be prompted for a password. But our command is executed in a script and we don't have a shell to enter the password! Luckily it is possible to setup sudo so no password is needed. Launch visudo to edit the configuration of sudo (If you have a favorite command-line editor you can set it temporary by executing 'export EDITOR=
Now add the following config rule to the configuration file:
This rule let you execute the /sbin/shutdown command on ALL hosts which are OWNED by ALL (=anyone) and part of group ALL (any group) and this without a password. Make sure you restart apache and then test it! if you get an warning 'Warning: SuexecUserGroup directive requires SUEXEC wrapper.' then install the extra package for suexec 'sudo apt-get install apache2-suexec' and try to restart apache again.
When the server is restarted you an browse to http://
export EDITOR=vi
sudo -E /usr/sbin/visudo
username ALL=(ALL:ALL) NOPASSWD: /sbin/shutdown
Test it
/etc/init.d/httpd restart
or
/etc/init.d/apache2 restart
Complete configuration file for apache:
Place it in a .conf file in the folder /etc/apache2/conf.d/ or /etc/httpd/conf.d/ (depending on your installation). For example shutdown.conf:
References
No comments:
Post a Comment