PHP shell_exec返回没有换行符的字符串

时间:2017-03-28 07:28:50

标签: php shell-exec

我正在使用shell执行来自PHP的shell脚本,如下所示:

$output = shell_exec('./intnacstat.sh "'.$ip.'" 2>&1');

intnacstat.sh结果是:

interface GigabitEthernet0/8
 description ISE dot1x Port
 switchport access vlan 70
 switchport trunk encapsulation dot1q
 switchport trunk native vlan 70
 switchport trunk allowed vlan 256
 switchport mode trunk
 authentication event fail action next-method
 authentication host-mode multi-host
 authentication open
 authentication order dot1x mab
 authentication priority dot1x mab
 authentication port-control auto
 authentication periodic
 authentication timer reauthenticate server
 authentication timer inactivity server
 authentication violation restrict
 mab

所以每个命令都在不同的行上。

但是当我在PHP上回显$ output时,一切都在一行上, 基本上不可读:

“show run interface G0 / 8构建配置...当前配置:767字节!接口GigabitEthernet0 / 8说明ISE dot1x端口switchport access vlan 70 switchport trunk封装dot1q switchport trunk native vlan 70 switchport trunk允许vlan 256 switchport模式trunk身份验证事件失败操作next-method身份验证主机模式多主机身份验证打开身份验证命令dot1x mab身份验证优先级dot1x mab身份验证端口控制自动身份验证定期身份验证计时器reauthenticate服务器身份验证计时器不活动服务器身份验证

有人能告诉我如何回显$ output以在命令末尾添加线制动器。 或者任何其他方式都可以做到。

3 个答案:

答案 0 :(得分:2)

尝试使用system

<?php
echo '<pre>';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('ls', $retval);

// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

说明:

system()函数

PHP中的系统函数接受一个带有要执行的命令的字符串参数以及您希望传递给该命令的任何参数。此函数执行指定的命令,并将任何结果文本转储到输出流(Web服务器情况下的HTTP输出,或者如果您将PHP作为命令行工具运行,则控制台)。如果它发出文本输出,则返回此函数是程序的最后一行输出。

exec()函数

系统功能非常有用且功能强大,但其中一个最大的问题是程序中的所有结果文本都直接转到输出流。在某些情况下,您可能希望格式化生成的文本并以不同的方式显示它,或者根本不显示它。

为此,PHP中的exec函数完全适应。它不是将正在执行的程序生成的所有文本自动转储到输出流,而是让您有机会将此文本放在第二个参数返回的数组中:

shell_exec()函数

到目前为止,我们执行的大多数程序或多或少都是真正的程序1。但是,Windows和Unix用户运行的环境实际上比这更丰富。 Windows用户可以选择使用Windows命令提示符程序cmd.exe此程序称为命令shell。

passthru()函数

PHP提供的一个与我们迄今为止看到的相似的功能是passthru功能。与其他函数一样,此函数执行您告诉它的程序。但是,它会立即将此程序的原始输出发送到PHP当前正在使用的输出流(即Web服务器方案中的HTTP或PHP命令行版本中的shell)。

proc_open()函数和popen()函数

proc_open()与popen()类似,但对程序执行提供了更大程度的控制。 cmd是shell要执行的命令。 descriptorspec是一个索引数组,其中键表示描述符编号,值表示PHP将该描述符传递给子进程的方式。管道将被设置为一个索引的文件指针数组,它对应于PHP创建的任何管道的末尾。返回值是表示进程的资源;你完成它后应该使用proc_close()释放它。

答案 1 :(得分:0)

尝试echo "<pre>". $output."</pre>";

提示:在显示格式不正常的文本时使用<pre>标记(包括换行符和使用print_r($arr)打印数组时)

答案 2 :(得分:0)

我认为结果是正确的,但被浏览器呈现为text/html

在打印header("Content-type: text/plain");之前添加$output