如何在系统,exec或shell_exec中运行多个命令?

问题描述:

我试图像这样从PHP运行shell命令:如何在系统,exec或shell_exec中运行多个命令?

ls -a | grep mydir 

但是PHP只使用第一个命令。有没有办法强制PHP将整个字符串传递给shell?

(我不关心输出)

+0

PHP不解析shell命令去除东西。你的代码是什么样的? – 2010-06-28 07:56:39

如果你想从该命令的输出,那么你可能要代替POPEN()函数:

http://php.net/manual/en/function.popen.php

http://www.php.net/manual/en/function.proc-open.php

首先打开ls -a读取输出,将其存储在av ar,然后打开grep mydir写入您从ls -a存储的输出,然后再次读取新的输出。

L.E:

<?php 
//ls -a | grep mydir 

$proc_ls = proc_open("ls -a", 
    array(
    array("pipe","r"), //stdin 
    array("pipe","w"), //stdout 
    array("pipe","w") //stderr 
), 
    $pipes); 

$output_ls = stream_get_contents($pipes[1]); 
fclose($pipes[0]); 
fclose($pipes[1]); 
fclose($pipes[2]); 
$return_value_ls = proc_close($proc_ls); 


$proc_grep = proc_open("grep mydir", 
    array(
    array("pipe","r"), //stdin 
    array("pipe","w"), //stdout 
    array("pipe","w") //stderr 
), 
    $pipes); 

fwrite($pipes[0], $output_ls); 
fclose($pipes[0]); 
$output_grep = stream_get_contents($pipes[1]); 

fclose($pipes[1]); 
fclose($pipes[2]); 
$return_value_grep = proc_close($proc_grep); 


print $output_grep; 
?> 

答案:

请避免这样的小事广泛的解决方案。这是它的解决方案: *因为它会很长时间在php中完成,然后在python中执行(使用subprocess.Popen在python中将占用三行),然后从php中调用python的脚本。

它在末端约七条线路,而问题最终得到解决:

脚本在Python中,我们把它叫做pyshellforphp.py

import subprocess 
import sys 
comando = sys.argv[1] 
obj = subprocess.Popen(comando, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) 
output, err = obj.communicate() 
print output 

如何从PHP调用python脚本:

system("pyshellforphp.py "ls | grep something");