0

我正在尝试通过 Laravel 调度程序每天从我的服务器上擦除敏感的历史命令

当我运行此代码时:

$schedule->exec(`for h in $(history | grep mysql | awk '{print $1-N}' | tac) ; do history -d $h ; done; history -d $(history | tail -1 | awk '{print $1}') ; history`)->{$interval}()->emailOutputTo($email)->environments('prod');

我收到此错误:

⚡️  app2020  php artisan schedule:run                                                                                                             
                                                                                                                                                   
   ErrorException                                                                                                                                  
                                                                                                                                                   
  Undefined variable: h                                                                                                                            
                                                                                                                                                   
  at app/Console/Kernel.php:44

注意到这是一个完美的工作命令

for h in $(history | grep mysql | awk '{print $1-N}' | tac) ; do history -d $h ; done; history -d $(history | tail -1 | awk '{print $1}') ; history

注意: 我知道我可以通过将上面的命令添加到 crontab 来实现它,但目标是让所有 cron 活动组织在 Laravel 项目中

既然 bash 和 PHP 使用$它们的变量,那么如何超越并使类似的 bash 命令起作用?

任何提示,我都会接受。

4

1 回答 1

3

您将命令包装在反引号中,这将插入变量并将值作为命令执行。这些东西你都不想要。

使用单引号构建命令,然后将其传递给exec().

$cmd =  'for h in $(history | grep mysql | awk \'{print $1-N}\' | tac) ;';
$cmd .= '    do history -d $h ;';
$cmd .= 'done;';
$cmd .= 'history -d $(history | tail -1 | awk \'{print $1}\') ;';
$cmd .= 'history';

$schedule
    ->exec($cmd)
    ->{$interval}()
    ->emailOutputTo($email)
    ->environments('prod');

对于更有效的方法,您可以尝试直接编辑历史文件。

$cmd = 'sed -i /mysql/d "$HOME/.bash_history"';

无需删除文件中的最后一个条目,因为它是交互式 shell 命令的历史。

显然,最好的办法是不要将“敏感”的东西放在命令行中。对于 MySQL,这可以通过向.my.cnf文件添加凭据来完成。

于 2020-12-04T21:14:01.523 回答