让网页执行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;
    }
}
相关推荐
Best-Wishes8 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
爱上网的小舟11 小时前
星际战士2启动错误怎么办?5种游戏报错解决方法
开发语言·php
唐青枫13 小时前
Yii2 Applications 详解:应用生命周期、组件配置与多入口实战
php
我是唐青枫13 小时前
Yii2 Controller 详解:路由、Action、过滤器与 CRUD 实战
php
Nathan__2716 小时前
PHP面试题——情景应用
开发语言·php
北京盛世宏博18 小时前
异地机房采集踩坑笔记:以太网温湿度记录仪跨网段通信调试实战
开发语言·笔记·单片机·php·传感器·温湿度
盛世宏博智慧档案21 小时前
IP 温湿度设备频繁断连?TCP 心跳保活机制调试与参数设置指南
网络·网络协议·tcp/ip·php·传感器·温湿度
Soari21 小时前
交换机转发模式
开发语言·网络·php
ESDWAN1 天前
海外股票网络环境优化与交易场景应用:从行情获取到交易系统稳定性设计
开发语言·网络·php
WeiXin_DZbishe1 天前
基于springboot宠物领养系统-计算机毕设 附源码【课程设计】94217
vue.js·spring boot·python·django·php·课程设计