【问题标题】:PHP: How to send ssh command and not wait until it is executed?PHP:如何发送 ssh 命令而不是等到它执行?
【发布时间】:2019-02-18 23:15:47
【问题描述】:

我有以下功能:

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)) }

sshcommand 函数如下所示:

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); }

我的问题是第一个更新函数要等到/var/script/config.sh 完成。

但在我的某些情况下需要很长时间,所以我只想发送命令并让它在后台运行。

我尝试将其更改为/var/script/config.sh | at now + 1 minute,但结果相同..

有什么想法吗?

【问题讨论】:

标签: php ssh


【解决方案1】:

尝试在您的命令中使用&

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

bash 手册页说:

如果命令被控制运算符 & 终止,shell 会在子 shell 的后台执行命令。 shell不等待命令完成,返回状态为0。

确保您为 user 使用的 shell 正在被 ssh 使用,支持它。

你也可以试试nohup:

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

这也可能依赖于 shell。 bash 有效。不确定即普通的sh

【讨论】:

  • 一开始我虽然是这样,但是脚本没有执行:(
  • 确保您使用支持该功能的 shell。或者,您可以使用nohup。我编辑了答案。
  • 谢谢,问题似乎出在 config.sh 中的 wget ..不知何故...没有 & wget 可以工作,如果我切换 wget 以 curl 脚本也可以工作。但遗憾的是 curl 无法处理我需要的东西,所以我必须找出 wget 到底是什么问题。
  • 好的,我最终得到了at now + 1 minute -f /var/data/setupplaylist.sh,它有效。
  • 您应该找到罪魁祸首,而不是用解决方法掩盖它。尝试使您的 wget 详细并在某处记录其输出。然后检查失败的原因
猜你喜欢
  • 2013-06-05
  • 1970-01-01
  • 2019-05-04
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 2019-12-06
相关资源
最近更新 更多