how to do a linux reboot from php file

前端 未结 7 2084
忘掉有多难
忘掉有多难 2020-12-19 10:53

I have a user brftv on my linux system and I have www-data that runs the nginx.

from the terminal I can let my brftv user run

sudo /sbin/reboot
         


        
7条回答
  •  忘掉有多难
    2020-12-19 11:14

    Giving reboot permission to www user is a bad idea.Create a cron and do system reboot from the cron rather than from PHP script. The Cron will run every minute and check for reboot flag. If it is set the it will do the reboot.

    1)write a flag to a file from your php program so that the cron can decide whether to do reboot or not.

     $Handle = fopen("/tmp/myfile", 'w');
     fwrite($Handle, "doreboot");
     fclose($Handle);
    

    2) Create a bash script to read that file and do reboot if the PHP script tells it to do so.

    #!/bin/bash
    arg=$(head -n 1 /tmp/myfile)   
    if [ "$arg" == "doreboot" ]; then
      >/tmp/myfile
      echo "Rebooting"
      echo 'password' | sudo -S reboot
    fi
    

    execute this in shell chmod +x mycron.sh

    3) Configure the script in crontab

    crontab -e and paste this

    * * * * * path/mycron.sh
    

    4) The user who set the cron should have sudo permission. Add him to sudoers.

提交回复
热议问题