在 Laravel 7 个调度程序上执行服务器命令

Execute Server Commands on Laravel 7 Scheduler

我的 Laravel 7 Scheduler

中有 2 个命令
$schedule->command('inspire')->everyMinute()->emailOutputTo(env('MAIL_TO'));
$schedule->exec('whoami')->everyMinute();

✅第一个works完美,收到邮件


❌ 这个第二个根本不行

$schedule->exec('whoami')->everyMinute();

我关注了:https://laravel.com/docs/7.x/scheduling

对我有什么提示吗?

暂时

我创造了这个

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class exec extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'exec {cmd}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run any command(s)';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $cmd = $this->argument('cmd');
        $this->info(shell_exec($cmd));
    }
}

并像这样使用它

$schedule->command('exec date')->everyMinute()->emailOutputTo(env('MAIL_TO'));
$schedule->command('exec history')->everyMinute()->emailOutputTo(env('MAIL_TO'));

有效!!

我的猜测是 whoami 运行正常,但没有对输出进行任何处理。

您可以尝试将 emailOutputTo(env('MAIL_TO')); 添加到第二个命令中,看看您是否会收到包含输出的电子邮件?

请查看有关从 exec 输出结果的文档:https://laravel.com/docs/7.x/scheduling#task-output

正如@Clément Bisaillon 所建议的那样,您忘记了为 shell 命令输出添加方法。

但是您的评论已被提出一个新问题。

为什么它适用于 whoiamdate,但不适用于 history

这个作品:

$schedule->exec('cat /home/abilogos/.bash_history ')->everyMinute()->appendOutputTo('/home/abilogos/Desktop/testHist.txt');

您可以在 echo $HISTFILE

中找到历史文件

但是为什么?

当您 which history 找到历史路径并告诉您那里时,它会变得更加有趣

which: no history in Your Path

喜欢source命令。

因为它们不是 Programs 存储在 $PATH 位置。他们是bash的命令

http://manpages.ubuntu.com/manpages/bionic/man7/bash-builtins.7.html

和 laravel 使用 php @proc_open (Symfony\Component\Process\Process) 只执行 Programs 而不是 Bash 命令 :

https://www.php.net/manual/en/function.proc-open.php