| 函數 | 返回值 | 輸出行為 | 適用場景 |
|---|---|---|---|
system() | 最後一行(字符串) | 直接輸出到瀏覽器/標準輸出 | 簡單命令、需即時顯示輸出 |
exec() | 最後一行(字符串),可選參數接收所有行數組 | 不自動輸出 | 捕獲輸出進一步處理 |
popen() | 文件指針(資源) | 管道讀/寫,需 pclose() 關閉 | 大數據流、雙向交互 |
$last = system('ls', $retval);
echo "Last line: $last\nReturn: $retval";
echo exec('whoami'); // 單行
$output = [];
$code = 0;
exec('ls -la', $output, $code); // $output 接收所有行
print_r($output);
$fp = popen('/bin/ls', 'r');
while (!feof($fp)) {
echo fgets($fp, 1024);
}
pclose($fp);
escapeshellarg() 或 escapeshellcmd() 轉義shell_exec、passthru、`反引號` 等高風險函數(disable_functions)Web 用戶無權執行 w/top 等命令。編寫 C 程序 setuid(root) 執行特權命令,PHP 調用該二進制。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
uid_t uid = getuid(), euid = geteuid();
if (setreuid(euid, uid)) perror("setreuid");
system("/usr/bin/w");
return 0;
}
gcc -o w -Wall w.c
chown root:root w
chmod u+s w # 設置 SUID
$last = exec('/usr/local/ismole/w', $output);
$load = explode("load average: ", $output[0])[1];
echo $load; // 輸出如 "0.15, 0.10, 0.05"
mysqldump + 壓縮推薦使用 SSH2 擴展(ssh2_exec)或 Ansible/SaltStack 遠程執行,避免本地 SUID 風險;容器化環境下用 docker exec / Kubernetes Job。