shell_exec() 无法执行某些命令

shell_exec() unable to execute certain commands

当我注意到我无法从以下内容中获得结果时,我只是在测试和摆弄安全性的东西:

<?php echo shell_exec('history'); ?>

同指:

<?php echo shell_exec('fc -l 1'); ?>

两者都在最后用 2>&1 尝试过,但毕竟 - history 不是命令。也在 CLI 下试过:

php -r "echo shell_exec('fc -l 1');"

没有 return 任何东西。也尝试使用 system()exec()(=没有 return 结果)。同时:

shell_exec()运行s sh。历史是其他 shell 中可用的扩展功能,例如 bashkshzsh,但通常在 sh 中不可用(在某些操作系统上,sh是 link 到 bash,但 bash 检查它是 运行 的名称,并在调用 sh 时禁用许多扩展名。

你可以这样做:

shell_exec("bash -c 'history'");

到运行bash并执行其history命令。

另请注意,历史记录机制通常仅在交互式 shell 中启用,而不是从程序调用的 shell。

找到答案了。似乎大多数 shell 早就将 history 命令作为 shell 内置 。来自维基百科:

A shell builtin is a command or a function, called from a shell, that is executed directly in the shell itself, instead of an external executable program which the shell would load and execute.

来源:https://en.wikipedia.org/wiki/Shell_builtin

PHP shell 标注由 sh 处理,但大多数理智的人使用 bash 将其历史存储在别处。同样,shell 历史通常仅在正常关闭期间由交互式 shell 写入。