【问题标题】:I need to run some bash from PHP webpage我需要从 PHP 网页运行一些 bash
【发布时间】:2012-08-24 13:21:14
【问题描述】:

我有一个如下的 bash 脚本:

#!/bin/bash
for i in `cat domains` ; do
tag=$(echo -n $i" -   "; whois $i | grep -o "Expir.*")
reg=$(echo -n -"     "; whois $i | grep "Registrar:")
echo $tag $reg

sleep .5s
done;

我希望有一个 php 页面,用户可以在其中粘贴域列表,当他们点击发送时,它会调用 bash 脚本处理域并返回输出。这可能吗?

【问题讨论】:

  • 迭代文本文件的首选方法是while read -r i; do ...; done < domains。见Bash FAQ 001

标签: php bash variables


【解决方案1】:

这是可能的,但是在执行带有用户输入的命令时需要小心。您可以使用exec() 或反引号从 PHP 在服务器上执行命令。

请注意确保用户输入的内容实际上是 URL,而不是用于在您的服务器上执行恶意命令的内容。


示例:

您的代码可能如下所示:

$output = array();
$urls = $_POST["urls"];
// perform necessary sanitation checks if needed
exec('/path/to/your/script '. implode(' ', $urls), $output);
echo $output;

【讨论】:

  • 我不太在意安全性,因为它是一个工作工具,只有 4 人可以访问它,而且他们在服务器上有根!
  • 变量扩展不会被重新扫描为命令,因此脚本无法执行恶意命令。但是,您仍然引用"$i" 以防止通配符被扩展。
  • @Barmar:但是他必须在 PHP 中执行一个命令来调用 bash 脚本,并且他必须将参数传递给那个 bash 文件。因此 PHP 可以执行恶意命令。对? (这更多是为了一般知识,因为 OP 已经表明它将在受控环境中使用)。
  • 我假设他正在运行上面的脚本,它不带任何参数,它只是从文件中读取。但是请参阅我在他的脚本的 PHP 版本中使用 addslashes
  • @Barmar:是的,我喜欢你的解决方案。
【解决方案2】:

是的,你可以使用exec()shell_exec() 命令

【讨论】:

  • 所以我需要查看 bash 脚本的输入,我该怎么做?
  • 看看proc_open,它允许你为进程的输入和输出提供管道。
【解决方案3】:

您真的需要运行 bash 脚本吗?这是等效的 PHP 代码:

foreach ($domains as $domain) {
  $domain = addslashes($domain);
  exec("whois '$domain'", $results);
  foreach ($results as $line) {
    if (preg_match('/Expir.*/', $line, $matches)) $tag = $matches[0];
    if (preg_match('/Registrar:/', $line)) $reg = $line;
  }
  echo $domain.' - '.$tag.' - '$reg."\n";
  usleep(500000);
}

【讨论】:

  • +1 - 我更喜欢这个解决方案,而不是依赖外部依赖。如果这就是 bash 脚本的全部功能,那么这似乎是一种更好的方法。
  • 哦,我错过了部分代码** reg=$(echo -n -" "; whois $i | grep "Registrar:") 应该是 **reg=$ (echo -n -" "; whois $i | grep -A1 "Registrar:" | tr -d '\n')
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多