从Symfony命令运行Linux命令

Maa*_*ckx 3 php linux command-line-interface symfony

如何在Symfony命令中运行简单的Linux命令?

我想ssh username@host -p port在命令结束时运行......

我试过了:

$input = new StringInput('ssh username@host -p port');
$this->getApplication()->run($input, $output);
Run Code Online (Sandbox Code Playgroud)

但是这引发了以下异常:`" - p"选项不存在.`

它似乎是在我的Symfony命令的相同"上下文"中执行的.

Ben*_*der 6

如何在Symfony命令中运行简单的Linux命令?

首先,尝试执行simple/plain命令(ls)以查看发生的情况,然后继续执行特殊命令.

http://symfony.com/doc/current/components/process.html

码:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('ls -lsa');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
Run Code Online (Sandbox Code Playgroud)

结果:

total 36
4 drwxrwxr-x  4 me me 4096 Jun 13  2016 .
4 drwxrwxr-x 16 me me 4096 Mar  2 09:45 ..
4 -rw-rw-r--  1 me me 2617 Feb 19  2015 .htaccess
4 -rw-rw-r--  1 me me 1203 Jun 13  2016 app.php
4 -rw-rw-r--  1 me me 1240 Jun 13  2016 app_dev.php
4 -rw-rw-r--  1 me me 1229 Jun 13  2016 app_test.php
4 drwxrwxr-x  2 me me 4096 Mar  2 17:05 bundles
4 drwxrwxr-x  2 me me 4096 Jul 24  2015 css
4 -rw-rw-r--  1 me me  106 Feb 19  2015 robots.txt
Run Code Online (Sandbox Code Playgroud)

如上所示,如果您将一段代码放在一个控制器中用于测试目的,请ls -lsa列出存储在web文件夹下的文件/文件夹!

你可以这样做shell_exec('ls -lsa');,这是我有时做的.例如shell_exec('git ls-remote url-to-my-git-project-repo master');


Ari*_*ris 5

这是 Symfony 5.2 中使用的更新界面。流程构造函数现在需要一个数组作为输入。

来源: https: //symfony.com/doc/current/components/process.html

Symfony\Component\Process\Process 类在子进程中执行命令,处理操作系统之间的差异并转义参数以防止安全问题。它取代了 exec、passthru、shell_exec 和 system 等 PHP 函数

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

$process = new Process(['ls', '-lsa']);
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
Run Code Online (Sandbox Code Playgroud)