让网页执行cmd命令

网页如何执行cmd命令,看似不能。其实现在已经可以了。

几个关键的要点。前端异步投递任务。php执行任务并返回结果给前端。

复制代码
<?php
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;

/**
 * Claude 命令 - 通过 proc_open 执行 claude CLI
 */
class ClaudeCmd extends Command
{
    protected function configure(): void
    {
        $this->setName('cmd')
            ->setDescription('通过 proc_open 执行 claude CLI 命令')
            ->addArgument('claude-args', Argument::OPTIONAL, '传递给 claude 的参数')
            ->addOption('dir', 'd', Option::VALUE_OPTIONAL, '指定工作目录', 'D:/code/tp8/tp8');
    }

    protected function execute(Input $input, Output $output): int
    {

        $claudeArgs = $input->getArgument('claude-args') ?: 'dir';

        $descriptors = [
            0 => ['pipe', 'r'],  // stdin
            1 => ['pipe', 'w'],  // stdout
            2 => ['pipe', 'w'],  // stderr
        ];

        $pipes = [];


        $output->writeln('执行: ' . $claudeArgs);

        $proc = proc_open(
             $claudeArgs,
            $descriptors,
            $pipes
        );

        if (!is_resource($proc)) {
            $output->writeln('<error>无法启动进程</error>');
            return 1;
        }

        // 关闭 stdin
        fclose($pipes[0]);

        // 读取输出
        $stdout = stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        $stderr = stream_get_contents($pipes[2]);
        fclose($pipes[2]);

        $exitCode = proc_close($proc);

        if (!empty($stderr)) {
            $output->writeln('<error>STDERR:</error>');
            $output->writeln($stderr);
        }

        if (!empty($stdout)) {
            $output->writeln('<info>STDOUT:</info>');
            $output->writeln($stdout);
        }

        $output->writeln('<info>退出码: ' . $exitCode . '</info>');

        return $exitCode;
    }
}
相关推荐
持敬chijing2 小时前
PHP开发-环境搭建-安装phpstudy-vscode工具
开发语言·vscode·php
Hello_Damon_Nikola4 小时前
AC7911从入门到精通
开发语言·嵌入式硬件·物联网·php
sbjdhjd6 小时前
大三网安秋招核心学习前言(AI 安全 + Web 漏洞 + 内网渗透全考点)
人工智能·网络协议·学习·安全·网络安全·开源·php
运维行者_6 小时前
企业带宽监控工具实战:网络流量分析与异常排查的5个关键能力
运维·服务器·开发语言·网络·分布式·后端·php
吴声子夜歌8 小时前
正则指引——PHP
开发语言·正则表达式·php
Claire_888 小时前
企业文件管理系统选型技术框架与主流产品对比分析
开发语言·php
COOLMO研究AI8 小时前
Python 如何给 AI API 实现断路器模式:防止雪崩与保护本地服务
人工智能·python·php
AC赳赳老秦9 小时前
网页公开附件自动采集:OpenClaw 批量下载页面内嵌 Word/Excel 附件,统一格式后结构化入库
java·python·word·php·excel·deepseek·openclaw
渣渣盟1 天前
当 Redis 写入成为性能瓶颈时,如何利用 异步批量 Sink 将吞吐量从 1w QPS 提升到 10w+?
数据库·redis·php