0

I have following function:

public function update($id){
   $data = $this->client_model->get_client_by_id($id);
   $sshport = $data['ssh_port'];
   $sshcommand = '/var/script/config.sh';
   $this->sshcommand($sshport, $sshcommand);
   $this->session->set_flashdata('msg', 'Config has been sent');
   redirect(base_url('admin/edit/'.$id)) }

The sshcommand function looks like this:

private function sshcommand($port, $command) {
 $remotecommand = 'ssh -q root@localhost -o "StrictHostKeyChecking=no" -p'.$port.' "'.$command.'" 2> /dev/null';
 $connection = ssh2_connect('controller.server.example.org', 22);
 ssh2_auth_pubkey_file($connection, 'root','/root/.ssh/id_rsa.pub','/root/.ssh/id_rsa');
 ssh2_exec($connection, $remotecommand); }

My problem is that the first update function wait till /var/script/config.sh has finished.

But in some of my cases it takes very long, so I just want to sent the command and let it work in the background.

I tried to change it to /var/script/config.sh | at now + 1 minute but its the same result..

Any Ideas?

fips123
  • 253
  • 2
  • 10
  • This is mostly related. Does this help? https://stackoverflow.com/questions/1019867/is-there-a-way-to-use-shell-exec-without-waiting-for-the-command-to-complete – Goose Feb 18 '19 at 13:58
  • 1
    Thanks, but I tried to redirect stdout and stderr too with no success. – fips123 Feb 18 '19 at 14:00

1 Answers1

1

Try using & with your command:

$sshcommand = '/var/script/config.sh &';

bash man page says:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

Ensure shell you are using for user that is being used by ssh, supports that.

Alternatively you can try with nohup:

$sshcommand = 'nohup /var/script/config.sh';

This may also be shell dependant. bash works. Not sure about i.e. plain sh though.

Marcin Orlowski
  • 67,279
  • 10
  • 112
  • 132
  • In the first moment I though this is it, but than the script is not executed :( – fips123 Feb 18 '19 at 14:27
  • Ensure you use shell that supports that. Alternatively you can use `nohup`. I edited the answer. – Marcin Orlowski Feb 18 '19 at 15:15
  • thanks, it seems the problem is wget inside the config.sh..somehow... without & wget works and if I switch wget to curl the script works too. But sadly curl can't handle what I need, so I have to find out what exactly the problem with wget is. – fips123 Feb 18 '19 at 19:00
  • Ok I ended up with `at now + 1 minute -f /var/data/setupplaylist.sh` which worked. – fips123 Feb 18 '19 at 19:19
  • you should find the culprit, not mask it with workaround. Try to make your wget verbose and log its output somewhere. Then check why it fails – Marcin Orlowski Feb 18 '19 at 23:46