【问题标题】:Php executing a bash script with at commandphp 使用 at 命令执行 bash 脚本
【发布时间】:2020-03-25 11:14:13
【问题描述】:

您好,我正在尝试在我的 php 脚本中执行 shell 命令,但它不起作用。 我的 php 脚本:

           //I save the Order 
            $holdedOrder->save();
            $id = $holdedOrder->id;
            $old_path = getcwd();
            chdir(__DIR__.'/../');
            $scriptFile = 'anacron_job_unhold_order.sh';
            $bool = file_exists($scriptFile);
            //$bool is true !

            //this command works in shell but not in here do not know why
            $s = shell_exec("echo \"/usr/bin/bash $scriptFile $id\" | /usr/bin/at now +$when");
            chdir($old_path);
            return [$s,$bool];

$when 具有有效值 4 hours4 days ... 命令将是:

echo bash anacron_job_unhold_order.sh 29 | at now +1 minutes

输出为空。使用exec() 尝试返回 127 代码

编辑: 我从 /etc/at.deny 中删除了 www-data 仍然是同样的问题

【问题讨论】:

  • 为什么是echo bash?使用exec(/usr/bin/bash $scriptFile..., $output); var_dump($output)进一步调试!
  • 退出代码127 表示找不到命令;)
  • 使用 at 命令连接 bash 将立即执行脚本,不会考虑 at 命令,但在执行 echo /bin/bash 脚本时 .. 将在特定时间执行脚本
  • 有什么帮助吗?

标签: php shell yii2 scheduled-tasks


【解决方案1】:

命令shell_exec("echo \"/usr/bin/bash $scriptFile $id\" | /usr/bin/at now +$when"); 可能是导致问题的原因,您应该仔细查看how at works

命令应该是这样的

at [options] [job...]

要通过命令而不是 STDIN 将作业分配给 at,请使用 heredoc syntax

at now + 1 minute <<< 'touch /tmp/test'

所以 PHP 代码应该是这样的;

$s = shell_exec("/usr/bin/at now + {$when} <<< '/usr/bin/bash {$scriptFile} {$id}'");
exec($s, $output, $return_var);

【讨论】:

  • @AhmedJaouadi 可能没有安装,尝试使用sudo apt-get install at 或尝试使用您的操作系统使用的包管理器。
猜你喜欢
  • 2021-11-17
  • 2020-04-30
  • 2016-12-27
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 2014-06-28
相关资源
最近更新 更多