Page 1 of 1

Reboot / Shutdown the server from PHP

Posted: Wed Jun 14, 2006 4:07 pm
by Ollie Saunders
I've recently starting running my own linux server :D

Its just for development purposes so at the end of the day I like to shut it down that usually means logging into ssh and typing "sudo reboot" or "sudo poweroff" followed by a prompt for my root password (i'm using ubuntu server, which incidently i highly recommend over fedora). Being the person that I am I thought "hey wouldn't it be cool to do this via my intranet with PHP" so I've been looking about for how to do this and trying stuff myself and so far I haven't been able to do it.

Here are some of my attempts:

Code: Select all

try {
	// i'm using the backtick operator here http://www.php.net/manual/en/language.o ... cution.php
	if(!$out = `sudo reboot\nrootpass`) throw new Exception('didn\'t work');
	echo $out;
}
catch(Exception $e) { errHandle($e); }

Code: Select all

try {
	if(!$out = `./scriptThatRebootsWhenRunFromSSH.sh`) throw new Exception('didn\'t work');
	echo $out;
}
catch(Exception $e) { errHandle($e); }

Code: Select all

try {
	$fh = fopen('php://stdin','w');
	if(!is_resource($fh)) throw new Exception('couldn\'t open stdin');
	try {
		if(!fputs($fh,"sudo reboot\nrootpass")) throw new Exception('couldn\'t write to stdin');
		fclose($fh);
	}
	catch(Exception $e) { errHandle($e); }
}
catch(Exception $e) { errHandle($e); }
I'd appreicate any help you can provide.
I stubbled across this solution but I don't really like the idea of something being cronned every minute:
A more easy solution is that:

Make a cron that executes every minut /tmp/rreboot.sh for user root
crontab -e
Add the line:
* * * * * /tmp/rreboot.sh

The script is:
/tmp/rreboot.sh
---------------
#!/bin/sh
if [ -f "/tmp/rreboot" ]; then
rm -f /tmp/rreboot
shutdown -r now
fi
---------------
Make executable the file with chmod +x /tmp/rreboot.sh

And a simple PHP like:
<?php
exec("echo rreboot > /tmp/rreboot");
echo "Ok, i'll reboot in a few seconds";
?>

So, when anyone calls to this PHP, creates a file, that if its detected by rreboot.sh, the root will reboot the machine.

Posted: Wed Jun 14, 2006 4:28 pm
by bokehman
I can't see how you can do it. PHP would need root authority over the command line.

Posted: Wed Jun 14, 2006 4:51 pm
by Christopher
You might want to take a look at the expect command.

Posted: Wed Jun 14, 2006 5:17 pm
by Ollie Saunders
I can't see how you can do it. PHP would need root authority over the command line.
Ahh so PHP can never be run as root?
Actually I'm glad if that is the case for security and all.
You might want to take a look at the expect command.
Yeah this may well do it so thank you. But I don't think my linux skills are up to compiling PHP just yet.