Jack Nicholson Jack Nicholson - 4 months ago 15
PHP Question

Restart NAMED/bind Service via Cronjob/bash in PHP

I simply want to restart named depending on whether a file exists. I've been stuck on this all day.

Command to create bash file:

$this->execute('echo -e "#!/bin/bash\nsudo /sbin/service named reload" >> /var/reload_named.sh');


Here is my cronjob:

*/1 * * * * cronjob: sudo sh /var/reload_named.sh; rm -f /var/reload_named.sh;


Here is what happens when the cronjob runs (
/var/log/cron
):

Jul 30 18:34:01 digitalocean CROND[24864]: (root) CMD (cronjob: sudo sh /var/reload_named.sh; rm -f /var/reload_named.sh )
Jul 30 18:34:01 digitalocean CROND[24862]: (root) UNSAFE (”example@digitalocean.com”)


For some reason it says it is
UNSAFE
. I've tried running with and without sudo.

It manages to delete the file but not restart named. I have tried doing so many other methods to get this to work.

I've tried (Over lots of Googling):


  • Running exec('service named restart') in php

  • Creating a .c file and adding a user that runs it from php

  • Running
    service named restart
    directly in
    crontab -e

  • Attempted different variations on running it with sudo

  • Tried adding apache user to sudo (Still fails)



Any help much appeciated

(I am on Centos 6.7)

Answer

I finally worked out a way to do this. Here is a method which SSHs into itself as root and runs service command:

$this->root_execute('service named reload');

    public function root_execute($command = '')
    {
        set_include_path('/path/to/dir/ssh/');
        require_once('Net/SSH2.php');

        $ssh = new Net_SSH2(SSH_HOST);

        if (!$ssh->login(SSH_USER, SSH_PASS)) {
            exit('failed');
        }
        $res = $ssh->exec($command);
        $ssh = null;
        restore_include_path();
        return $res;
    }

(Unfortunately doesn't work with HTTPD if running from http .php)