【问题标题】:How to include shell command in shell_exec function?如何在 shell_exec 函数中包含 shell 命令?
【发布时间】:2018-01-22 18:19:01
【问题描述】:

我正在尝试使用 PHP 覆盖远程服务器中的 .txt file。我使用的 Linux 命令在 bash 脚本中运行良好。但是shell_exec() 就不行了。

命令如下:

$number = $_GET["phone"];   
$out = shell_exec("echo $number | ssh root@0.0.0.0 '"cat > /path/to/file/number.txt"'");
echo $out;

请注意,两台服务器之间的密钥已经共享。因此 ssh 命令无需输入密码即可工作。

【问题讨论】:

  • 在单引号中尝试双引号:shell_exec('echo ..."cat..."')
  • 这段代码真的运行了吗?请包括它产生的任何错误或输出。
  • 这适用于简单的shell命令,如shell_exec(pwd); 但对于上述命令,它不起作用并且没有显示任何错误。

标签: php linux bash shell ssh


【解决方案1】:

例如,您可以使用反引号运算符来替代 shell 命令。

out = shell_exec('ls -alrt')
echo "$out"

shell_exec() 它将所有输出流作为字符串返回。


问题是您没有在导致问题的正确位置关闭报价。

一个示例脚本,并在更改命令中的引号时获得一些灵感。

$page = shell_exec("/tmp/script.sh '".$my_url."'");

【讨论】:

  • 还是不行。 shell_exec("echo $number") 工作正常。但是shell_exec("echo $number > /a.txt") 也不起作用。
  • 为什么shell_exec("echo $number > /a.txt") 不起作用?
  • @PiyumiGuruge,运行上述命令时出现什么错误?
  • 什么都没有。提交值时,它只是重定向到空白页面。但是在给定位置没有创建任何 .txt 文件。 shell_exec("echo $number") 给出了显示的数字,而不是浏览器中的空白页。
  • <?php if(isset($_GET['phone'])) { $number = $_GET["phone"]; //$out = "echo $number | ssh root@0.0.0.0 "cat > /path/to/file/number_bkp.txt""; $out = shell_exec("echo $number > /number_bkp.txt"); echo "$out"; } ?>
猜你喜欢
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 2014-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多