Search code examples
phpsshremote-accessshutdownphpseclib

Remote shutdown using PHP and SSH


What I want is a PHP file that I can call that shuts a computer down using SSH. Simple as that. Below is something that I've knocked up. Obviously, it doesn't work. I'm no PHP expert. Maybe a PHP expert could show me how to get it working. Thanks.

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('192.168.1.124');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

$ssh->write("sudo shutdown -h now");
sleep(5);
$ssh->write("password\n");

?>

Solution

  • I ended up finding a way to shutdown the computer safely using an AppleScript.

    The PHP file is:

    <?php
    include('Net/SSH2.php');
    
    $ssh = new Net_SSH2('192.168.1.124');
    if (!$ssh->login('josephftaylor', 'password')) {
        exit('Login Failed');
    }
    
    echo $ssh->exec('osascript Documents/shutdown.scpt');
    
    ?>
    

    The AppleScript is saved in my documents and is:

    tell application "System Events"
        shut down
    end tell
    

    Hope this helps anyone else trying to do something similar to me. Thanks for everyone's help!