萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 直接執行 Shell 指令完整指南:shell_exec、proc_open 與安全實務

PHP 執行系統指令是強大但高風險的功能。本文詳細說明 `shell_exec`、`exec`、`passthru`、`proc_open` 差異、輸出捕獲技巧、權限控管與資安加固原則。

常用函式對比

函式回傳值輸出處理適用場景
shell_exec完整輸出字串 / false自動捕獲 stdout+stderr簡單指令、需完整輸出字串
exec最後一行輸出;陣列參數可取得所有行需傳陣列參數捕獲需逐行處理、取得退出碼
passthru退出碼直接輸出到瀏覽器/標準輸出二進位輸出 (圖片、PDF)、串流
proc_open資源控制陣列雙向管道、非阻塞、進程控制複雜互動、長時間運行、需 stdin 傳入

關鍵技巧:捕獲 stderr (2>&1)

預設僅捕獲 stdout。若指令寫入 stderr(錯誤、警告、進度),PHP 會收到空字串。解決:在指令末尾加上 2>&1 將 stderr 重導向 stdout。

<?php
// 正確:捕獲完整輸出 (stdout + stderr)
$output = shell_exec("sudo /usr/local/nginx/sbin/nginx -t 2>&1");
echo "執行結果:
" . nl2br(htmlspecialchars($output));

proc_open 進階範例:雙向通訊、超時控制、非阻塞

<?php
function runCommandWithTimeout($cmd, $timeout = 30, $stdin = '') {
    $descriptors = [
        0 => ['pipe', 'r'],  // stdin
        1 => ['pipe', 'w'],  // stdout
        2 => ['pipe', 'w'],  // stderr
    ];
    $proc = proc_open($cmd, $descriptors, $pipes);
    if (!is_resource($proc)) throw new RuntimeException("proc_open 失敗: $cmd");

    // 寫入 stdin
    if ($stdin !== '') {
        fwrite($pipes[0], $stdin);
    }
    fclose($pipes[0]);

    // 非阻塞讀取
    stream_set_blocking($pipes[1], false);
    stream_set_blocking($pipes[2], false);

    $stdout = ''; $stderr = '';
    $start = time();
    while (true) {
        $read = [$pipes[1], $pipes[2]];
        $write = null; $except = null;
        if (stream_select($read, $write, $except, 0, 200000)) { // 0.2 秒
            foreach ($read as $pipe) {
                $data = fread($pipe, 8192);
                if ($pipe === $pipes[1]) $stdout .= $data;
                else $stderr .= $data;
            }
        }
        $status = proc_get_status($proc);
        if (!$status['running']) break;
        if (time() - $start > $timeout) {
            proc_terminate($proc, SIGKILL);
            throw new RuntimeException("指令超時: $cmd");
        }
        usleep(50000);
    }
    fclose($pipes[1]); fclose($pipes[2]);
    $returnCode = proc_close($proc);
    return ['stdout' => $stdout, 'stderr' => $stderr, 'code' => $returnCode];
}

// 使用
try {
    $result = runCommandWithTimeout('php -r "sleep(5); echo \"done\";"', 3);
} catch (RuntimeException $e) {
    echo $e->getMessage(); // 指令超時
}

資安鐵律:輸入驗證與指令注入防護

  1. 絕不直接拼接使用者輸入:`shell_exec("ping $ip")` → 攻擊者輸入 `8.8.8.8; rm -rf /`
  2. 使用 `escapeshellarg()` / `escapeshellcmd()`:
    $ip = escapeshellarg($_GET['ip']); // 單一參數加單引號並跳脫
    $output = shell_exec("ping -c 3 $ip");
  3. 白名單驗證:IP 格式、檔名格式、指令參數枚舉值。
  4. 最小權限原則:PHP-FPM 以低權限使用者運行(`www-data`),禁用 `sudo` 或嚴格限制 `sudoers` (NOPASSWD 特定指令)。
  5. 禁用危險函式:`php.ini` → `disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source` (視需求保留)。

常見場景最佳實踐

場景推薦函式關鍵點
健康檢查/狀態查詢shell_exec2>&1 捕獲 stderr、逾時控制
影像處理proc_open串流處理大檔、非阻塞、進度回報
批次匯入/ETLproc_open + 背景程序nohup/setsid 脫離終端、PID 檔管理
系統管理操作sudo + 白名單sudoers 僅允許特定指令、參數驗證

「能用 PHP 原生函式/擴充庫解決,就不要呼叫 Shell」。必須呼叫時,嚴守「輸入白名單、參數跳脫、最小權限、輸出捕獲」四大鐵律。

copyright © 萬盛學電腦網 all rights reserved