深入解析exec、system、passthru、shell_exec、proc_open、popen等核心函数,覆盖命令注入防护、安全执行策略、性能优化技巧与真实场景实践
exec() 是PHP中最常用的执行外部程序的函数之一,它将命令传递给操作系统并返回最后一行输出,同时可通过第二个参数获取完整输出数组,第三个参数可捕获返回状态码。该函数**不会直接输出结果到浏览器**,因此适合需要进一步处理输出的场景。
基本语法:
string exec(string $command, array &$output = ?, int &$result_code = ?)
<?php
$command = 'ls -l /var/www';
exec($command, $output, $return_var);
if ($return_var === 0) {
echo "命令执行成功\n";
print_r($output);
} else {
echo "命令执行失败,返回码: $return_var\n";
}
?>
⚠️ 注意:若命令中包含用户输入(如$_GET、$_POST),必须进行严格过滤,否则极易引发命令注入漏洞!建议使用escapeshellarg()或escapeshellcmd()进行转义。
exec()结合proc_open()实现复杂构建逻辑,例如自动部署、日志分析等。
system() 与exec()类似,但其最大区别在于:**它会直接将命令输出实时打印到浏览器**,并返回命令执行结果的最后一行。适合需要实时反馈的场景,如构建工具、监控脚本等。
基本语法:
string system(string $command, int &$result_code = ?)
<?php
header('Content-Type: text/plain');
system('ping -c 4 www.example.com', $ret);
echo "\n返回状态码: $ret\n";
?>
⚠️ 安全警告:当用户可控制$command参数时,攻击者可通过注入分号;、管道|或反引号`执行任意命令,例如:
ping -c 4 www.example.com; cat /etc/passwd
escapeshellarg()处理命令参数,如:$host = escapeshellarg($_GET['host']);system("ping -c 4 $host");
passthru() 专门用于执行需要返回原始二进制数据的命令(如图像生成、文件打包),它不返回输出内容,而是直接传递给浏览器,适合与header()配合生成动态内容。
基本语法:
void passthru(string $command, int &$result_code = ?)
<?php
$zip_path = '/tmp/report.zip';
$dir = escapeshellarg('/var/www/reports');
// 使用系统zip命令打包
passthru("zip -r $zip_path $dir", $return);
if ($return === 0 && file_exists($zip_path)) {
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($zip_path));
header('Content-Disposition: attachment; filename="report.zip"');
readfile($zip_path);
unlink($zip_path);
} else {
die('打包失败');
}
?>
💡 典型应用场景:图像处理(ImageMagick)、PDF生成(wkhtmltopdf)、音视频转码(ffmpeg)等依赖系统命令的扩展功能。
shell_exec() 通过shell执行命令,并返回完整输出(包括标准输出和错误输出),若命令无输出则返回NULL。与exec()相比,它不捕获状态码,但输出更完整。
基本语法:
string shell_exec(string $command)
<?php
$load = shell_exec('cat /proc/loadavg');
echo "系统负载:$load\n";
// 获取PHP版本信息(跨平台)
$phpver = shell_exec('php -v');
echo "$phpver\n";
?>
⚠️ 注意:在Windows系统中,shell_exec()默认使用cmd.exe,而在Linux中使用/bin/sh。若需跨平台兼容,建议使用escapeshellarg()处理参数。
proc_open() 是PHP中功能最强大的命令执行函数,支持创建子进程并控制其标准输入、输出、错误流,适用于需要交互式命令执行的场景(如SSH模拟、交互式脚本)。
基本语法:
resource proc_open(string $command, array $descriptor_spec, array &$pipes)
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
$process = proc_open('cat', $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], "Hello\nWorld\n");
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$return_value = proc_close($process);
echo "输出: $stdout\n";
echo "错误: $stderr\n";
echo "返回码: $return_value\n";
}
?>
💡 优势:可实现完全自定义的进程间通信(IPC),避免命令注入风险(通过管道直接传递数据而非拼接字符串)。
popen() 创建一个指向命令的单向管道(读或写),常用于逐行处理命令输出(如日志分析)。返回一个文件指针资源,可用fgets()、fread()等读取,或fwrite()写入。
基本语法:
resource popen(string $command, string $mode)
<?php
$handle = popen('ps aux', 'r');
while (!feof($handle)) {
$line = fgets($handle, 4096);
if (strpos($line, 'php') !== false) {
echo "发现PHP进程:$line\n";
}
}
pclose($handle);
?>
⚠️ 注意:mode只能是'r'(读)或'w'(写),不支持双向通信;若需双向通信,应使用proc_open()。
反引号是shell_exec()的简写形式,直接在字符串中执行shell命令并返回输出。适用于简单脚本,但可读性较差,不推荐在大型项目中使用。
<?php
$timestamp = `date +%s`;
echo "当前时间戳:$timestamp\n";
// 与shell_exec等效
$timestamp = shell_exec('date +%s');
?>
⚠️ 安全风险与shell_exec()完全相同,必须严格过滤输入!
pcntl_exec() 在当前进程中执行新程序,**替换当前进程镜像**(类似Unix的exec系统调用),常用于多进程编程中的子进程创建。
基本语法:
void pcntl_exec(string $path, array $args = [], array $envs = [])
<?php
$pid = pcntl_fork();
if ($pid == 0) {
// 子进程
pcntl_exec('/usr/bin/php', ['worker.php', 'task1']);
} elseif ($pid > 0) {
// 父进程
pcntl_wait($status);
echo "子进程已退出\n";
}
?>
💡 限制:仅在启用pcntl扩展的CLI模式下可用,Web SAPI中不可用。
通过输出缓冲(Output Buffering)可捕获system()的实时输出,实现“既显示又处理”的效果,常用于Web界面中的命令执行监控。
<?php
ob_start();
system('npm run build', $ret);
$output = ob_get_clean();
if ($ret === 0) {
echo "构建成功!\n";
echo "输出内容:\n$output\n";
} else {
echo "构建失败!错误日志:\n$output\n";
}
?>
💡 优化技巧:结合flush()和ob_flush()可实现前端实时刷新(需禁用输出压缩)。
当命令输出极大(如全盘扫描)时,避免一次性加载到内存,应使用流式读取。
<?php
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$process = proc_open('find /var -name "*.log" -mtime +30', $descriptorspec, $pipes);
if (is_resource($process)) {
while (!feof($pipes[1])) {
$line = fgets($pipes[1]);
echo "超期日志:$line\n";
// 实时处理,不占用内存
flush();
ob_flush();
}
proc_close($process);
}
?>
💡 优势:内存占用恒定,适合处理TB级日志。
配合proc_open()可实现进程优先级调整与强制终止,适用于长时间运行的任务(如数据迁移)。
<?php
$process = proc_open('mysqldump --all-databases > backup.sql',
array(0 => array("pipe", "r"), 1 => array("pipe", "w")), $pipes);
if (is_resource($process)) {
// 降低进程优先级(nice值+10)
proc_nice(10);
// 5秒后终止(模拟超时)
usleep(5000000);
proc_terminate($process, SIGTERM);
proc_close($process);
}
?>
⚠️ 注意:proc_nice()需权限支持,非root用户可能无法降低nice值。
返回子进程的运行状态(是否运行、CPU时间、退出码等),适合进度跟踪与异常检测。
<?php
$process = proc_open('ffmpeg -i input.mp4 output.mp4',
array(0 => array("pipe", "r"), 1 => array("pipe", "w")), $pipes);
$status = proc_get_status($process);
while ($status['running']) {
echo "进程运行中...\n";
echo "CPU时间:{$status['cpu_time']}秒\n";
// 每3秒检查一次
sleep(3);
$status = proc_get_status($process);
}
?>
💡 实战:用于Web界面显示“转换中...”,避免用户以为页面卡死。
escapeshellarg()转义参数,escapeshellcmd()转义整个命令set_time_limit() + proc_terminate())disable_functions配置项)| 方法 | 输出处理 | 状态码 | 实时输出 | 安全风险 | 适用场景 |
|---|---|---|---|---|---|
exec() |
返回最后一行,数组存全部 | ✅ 可获取 | ❌ 不实时 | 高 | 需处理输出的后台任务 |
system() |
直接输出,返回最后一行 | ✅ 可获取 | ✅ 实时 | 高 | 实时监控脚本 |
passthru() |
原始二进制输出 | ✅ 可获取 | ✅ 原始流式 | 高 | 二进制内容生成(图像/PDF) |
shell_exec() |
返回完整字符串 | ❌ 不可获取 | ❌ 不实时 | 高 | 简单命令输出捕获 |
proc_open() |
完全自定义流控制 | ✅ 可获取 | ✅ 可控 | 低 | 交互式进程、复杂IPC |
popen() |
单向管道读写 | ❌ 不可获取 | ✅ 逐行读取 | 中 | 日志分析、流处理 |
`backticks` |
同shell_exec() |
❌ 不可获取 | ❌ 不实时 | 高 | 简单脚本快速实现 |
pcntl_exec() |
替换当前进程 | ✅ 可获取 | ❌ 不适用 | 低 | CLI多进程编程 |
proc_open()或exec()(配合严格过滤);对于CLI脚本,可安全使用pcntl_exec();避免在用户可控输入中使用反引号或system()。
攻击者通过在表单中输入127.0.0.1; cat /etc/passwd,使ping -c 4 $ip变为:
ping -c 4 127.0.0.1; cat /etc/passwd
使用正则白名单校验参数:
if (!preg_match('/^[a-zA-Z0-9\.\-]+$/', $ip)) { die('非法IP格式'); }
对拼接前的参数使用escapeshellarg():
$safe_ip = escapeshellarg($ip); system("ping -c 4 $safe_ip");
在Docker容器中执行命令,限制文件系统、网络权限:
docker run --rm -v $(pwd):/app php:8-cli ping -c 4 $ip
在/etc/php/8.1/apache2/php.ini中设置:
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,escapeshellcmd,escapeshellarg,pcntl_exec
⚠️ 注意:若业务依赖exec()等函数(如Composer),需谨慎禁用,可改用沙箱执行。
| 绕过方式 | 示例 | 防御方案 |
|---|---|---|
| 编码绕过 | echo 'Y2F0IC9ldGMvcGFzc3dk' | base64 -d | sh |
禁止执行base64、eval等工具 |
| 路径绕过 | /bin/sh -c 'ls' |
限制$PATH环境变量 |
| 换行绕过 | ls\n-rf / |
过滤\n、\r、\t等控制字符 |
| 命令替换 | $(cat /etc/passwd) |
禁用反引号与$()语法 |
场景:分析Nginx访问日志,统计高频IP
<?php
$logs = shell_exec("grep 'GET /api/user' /var/log/nginx/access.log | awk '{print \$1}' | sort | uniq -c | sort -rn | head -10");
echo "<h3>高频访问IP</h3><pre>$logs</pre>";
// 解析为数组
$ips = [];
foreach (explode("\n", trim($logs)) as $line) {
if (preg_match('/(\d+)\s+(\d+\.\d+\.\d+\.\d+)/', $line, $m)) {
$ips[$m[2]] = (int)$m[1];
}
}
print_r($ips);
?>
<?php
// 生成带水印的缩略图
$source = escapeshellarg($_POST['image']);
$watermark = escapeshellarg('/var/www/watermark.png');
$output = escapeshellarg('/tmp/thumb_' . uniqid() . '.jpg');
passthru("convert $source -resize 800x600 -gravity southeast -composite $watermark $output", $ret);
if ($ret === 0) {
header('Content-Type: image/jpeg');
readfile("/tmp/thumb_*.jpg");
}
?>
<?php
$process = proc_open('crontab -l', [
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
], $pipes);
if (is_resource($process)) {
$output = stream_get_contents($pipes[1]);
echo "<h3>当前计划任务</h3><pre>$output</pre>";
proc_close($process);
}
?>
<?php
$handle = popen("find /var/www -name '*.php' -mtime -7 -type f", "r");
echo "<h3>最近7天修改的PHP文件</h3><ul>";
while (!feof($handle)) {
$file = trim(fgets($handle));
if ($file) {
echo "<li>$file</li>";
flush();
}
}
echo "</ul>";
pclose($handle);
?>
<?php
$db = escapeshellarg('production');
$backup = "/backups/db_$(date +%Y%m%d).sql.gz";
$return_var = 0;
exec("mysqldump --single-transaction $db | gzip > $backup", $output, $return_var);
if ($return_var === 0) {
echo "备份成功:$backup\n";
} else {
error_log("备份失败:" . implode("\n", $output));
die("备份失败,请检查数据库连接");
}
?>
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
$process = proc_open('git pull origin main', $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], "yes\n"); // 处理密钥确认
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$status = proc_close($process);
echo "<pre>输出:$stdout\n错误:$stderr</pre>";
}
?>
<?php
$commands = [
'hostname' => 'hostname',
'内存使用' => 'free -h | grep Mem',
'磁盘使用' => 'df -h /',
'运行时间' => 'uptime -p'
];
echo "<table class='method-table'><thead><tr><th>指标</th><th>值</th></tr></thead><tbody>";
foreach ($commands as $label => $cmd) {
$output = [];
exec($cmd, $output);
echo "<tr><td>$label</td><td>" . implode('<br>', $output) . "</td></tr>";
}
echo "</tbody></table>";
?>
<?php
$process = proc_open('timeout 5s whoami', [
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
], $pipes);
if (is_resource($process)) {
$output = stream_get_contents($pipes[1]);
proc_close($process);
echo "<strong>当前用户:</strong> $output";
}
?>
<?php
// 非阻塞执行构建
exec("nohup /var/www/build.sh > /dev/null 2>&1 &");
http_response_code(202);
echo json_encode(['status' => 'build started']);
?>
<?php
$cmd = PHP_OS_FAMILY === 'Windows'
? 'ipconfig /all'
: 'ip addr show';
$output = shell_exec($cmd);
echo "<pre>$output</pre>";
?>
<?php
// 测试10次exec
$start = microtime(true);
for ($i=0; $i<10; $i++) {
exec('echo test', $o, $r);
}
$exec_time = microtime(true) - $start;
// 测试10次proc_open
$start = microtime(true);
for ($i=0; $i<10; $i++) {
$p = proc_open('echo test', [[0,'r'],[1,'w'],[2,'w']], $pipes);
fclose($pipes[0]);
fclose($pipes[1]);
proc_close($p);
}
$proc_time = microtime(true) - $start;
echo "exec: " . round($exec_time*1000, 2) . "ms\n";
echo "proc_open: " . round($proc_time*1000, 2) . "ms\n";
?>
💡 结果:在简单命令中exec()更快;在复杂交互中proc_open()更稳定。
<?php
function safe_exec($cmd, $args = []) {
$safe_args = array_map('escapeshellarg', $args);
$full_cmd = $cmd . ' ' . implode(' ', $safe_args);
// 记录日志
$log_entry = date('Y-m-d H:i:s') . " | User:" . $_SESSION['user']
. " | Cmd:$full_cmd | IP:" . $_SERVER['REMOTE_ADDR'] . "\n";
file_put_contents('/var/log/cmd_audit.log', $log_entry, FILE_APPEND);
return shell_exec($full_cmd);
}
// 使用示例
echo safe_exec('ls', ['-l', '/var/log']);
?>
exec()默认不输出到浏览器,需通过第二个参数获取输出数组:
$output = []; exec('ls', $output); print_r($output);
若需实时输出,改用system()或ob_start() + system()组合。
编辑php.ini:
disable_functions = exec,passthru,shell_exec,system,proc_open,popen
⚠️ 注意:某些框架(如Composer)依赖exec(),禁用前需测试兼容性。
使用WAF规则监控:
if (preg_match('/[;|&`$(){}[\]\x00-\x1F]/', $_GET['cmd'])) { die('非法输入'); }
建议使用escapeshellarg() + 白名单双重校验。
Windows使用cmd.exe,需注意:
- 路径用双引号包裹(exec("dir \"C:\Program Files\""))
- 避免使用正斜杠(/),改用反斜杠(\)
- 检查safe_mode和disable_functions配置
方法1:用system() + ob_flush()
方法2:用proc_open() + stream_set_blocking($pipes[1], false)
方法3:用exec() + tail -f模拟(需文件中转)
exec()返回最后一行,shell_exec()返回完整输出;exec()可获取状态码,shell_exec()不能。
使用timeout命令(Linux):
exec("timeout 5s long_task.sh", $output, $ret);
或用set_time_limit(5)配合proc_terminate()。
必须同时关闭所有管道:
fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]);
否则子进程可能因管道满而阻塞。
使用非root用户运行:
docker run --user 1000:1000 php:8-cli exec('whoami')
挂载只读卷:
-v /app:/app:ro
CLI模式:
- 无输出缓冲限制
- 可用pcntl_exec()
- 环境变量更完整
Web模式:
- 受max_execution_time限制
- 可能被Web服务器中断