如何获取控制台上显示的命令输出?
<?php
ob_start();
system('faxstat -s' , $retval);
$last_line = ob_get_contents();
ob_end_clean();
preg_match('/^32.+'s{9}(.*)/m', $last_line, $job_id);
?>
在控制台中,输出如下所示:
JID Pri S Owner Number Pages Dials TTS Status
36 127 R www-da 0xxxxxxxx 0:1 0:12
32 127 R www-da 0xxxxxxxx 0:1 0:12
35 127 R www-da 0xxxxxxxx 0:1 0:12
但在 PHP 中,$last_line
的回声是这样的:
JID Pri S 所有者号码页 拨号 TTS 状态 36 127 R www-da 0xxxxx 0:1 0:12 32 127 R www-da 0xxxxxx
0:1 0:12 35 127 R www-da 0xxxxx 0:1 0:12
注意:我不想打印输出,所以不需要<pre>
标签。我想preg_match
它。因为它丢失了格式,所以我的正则表达式毫无用处。
您需要
将exec与通过引用传递给它的变量一起使用,以捕获输出行。
$lastLine = exec('df -h',$output);
exec 只返回它引用的最后一行作为它的返回值,你会在 $output 参数中找到命令 exec 的完整输出(你通过引用提供的变量,exec() 转换为数组并填充,另见 PHP:参考解释)
例如
<?php
$lastLine = exec('df -h',$output);
print "'n$lastLine'n";
print_r($output);
将打印
none 990M 0 990M 0% /var/lock
Array
(
[0] => Filesystem Size Used Avail Use% Mounted on
[1] => /dev/sda1 145G 140G 5.8G 97% /
[2] => none 981M 668K 980M 1% /dev
[3] => none 990M 3.4M 986M 1% /dev/shm
[4] => none 990M 240K 989M 1% /var/run
[5] => none 990M 0 990M 0% /var/lock
)
因此,如您所见$lastLine实际上是命令打印的最后一行
我不明白为什么shell_exec或反引号对你不起作用,对不起。
现在对于您的解析模式:
<?php
// was stil using your posted 'wrong output'
$output = "JID Pri S Owner Number Pages Dials TTS Status 36 127 R www-da 0xxxxxxxx 0:1 0:12 32 127 R www-da 0xxxxxxxx
0:1 0:12 35 127 R www-da 0xxxxxxxx 0:1 0:12";
// we just strip the header out
$header = "JID Pri S Owner Number Pages Dials TTS Status ";
$headerless = str_replace($header,'',$output);
$pattern = '/([0-9]+)'s+([0-9]+)'s+([A-Z]+)'s+([^'s]+)'s+([^'s]+)'s+([0-9:]+)'s+([0-9:]+)/m'; // m to let it traverse multi-line
/*
we match on 0-9 whitespace 0-9 WS A-Z 'Anything not WS' WS ANWS WS 0-9:0-9 WS 0-9:0-9
*/
preg_match_all($pattern,$headerless,$matches);
print_r($matches);
这将为您提供所有单独的元素。显然,当您使用 exec 在数组中返回它时,您不需要剥离标头以及所有这些,但在我看来,该模式应该可以正常工作。
如果你不想输出任何东西,你也可以使用 exec()
.但是$last_line
将仅包含命令打印的实际最后一行。如果要处理整个输出,可以将其重定向到第二个参数为 exec()
的数组。
使用反引号运算符 (') 应保留输出格式。
$lastline = `ls`;
很难说没有看到您用于匹配的正则表达式。 我的猜测是,您正在尝试匹配不在此转换字符串中的非打印字符。 尝试匹配 ''s,这将查找几种类型的空格字符。