让网页执行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;
    }
}
相关推荐
IT召唤狮8 小时前
开源企业级零信任项目Pangolin,零信任能挡住PHP核弹漏洞吗?
开发语言·开源·php
大鹏说大话13 小时前
PHP 大文件上传解决方案:分片上传完整思路
开发语言·php
niucloud-admin14 小时前
NIUCLOUD PHP SAAS上门家政使用文档--服务订单:订单回访
php
大黄说说16 小时前
Composer 常见报错汇总:镜像、依赖冲突、环境坑一站式排查
php·composer
安易算力16 小时前
智算中心网络架构:RDMA/IB/以太网选型深度解析与优化实践
网络·架构·php
程序员大雄学编程17 小时前
Linux 磁盘满了怎么排查?df / du / find 三步定位大文件
linux·运维·php
fengci.19 小时前
CTF2困难部分
开发语言·网络·python·安全·php
大黄说说19 小时前
PHP 异步怎么实现?Swoole、Workerman 使用场景对比
开发语言·php·swoole
乐橙开放平台19 小时前
跨地域监控难管理?通过 GB28181 把各地海康大华乐橙摄像头注册到云端平台
开发语言·笔记·物联网·自动化·php·音视频·智能家居
广东融科数据服务有限公司20 小时前
网络监控经常卡顿、掉线、画面模糊?一线排查问答实录
开发语言·网络·php