通过API获取Docker EXEC的输出

问题描述 投票:0回答:0

我正在编写一个 C 函数来获取参数“容器名称”和“命令”以在指定容器内运行命令并返回输出。我正在使用 libdocker 通过 curl 调用 Restful API。目前该命令可以成功执行,但我不知道如何重定向和捕获输出。这是我的代码:

char * docker_exec(const char * name, const char * cmd) {
    json_error_t error;
    DOCKER *docker = docker_init(DOCKER_API_VERSION);
    DOCKER *docker2 = docker_init(DOCKER_API_VERSION);
    char url[100];
    long http_status = 0;
    char postdata[1024];

    // Create exec instance
    sprintf(postdata, "{\"AttachStdout\":true,\"AttachStderr\":true,\"Cmd\":[\"%s\"]}", cmd);
    sprintf(url, "http://%s/containers/%s/exec", DOCKER_API_VERSION, name);
    CURLcode response = docker_post_with_http_status(docker, url, postdata, &http_status);

    // Start exec instance with its ID
    json_t * j_id = json_loads(docker_buffer(docker), JSON_COMPACT, &error);
    sprintf(url, "http://%s/exec/%s/start", DOCKER_API_VERSION, 
    json_string_value(json_object_get(j_id, "Id")));
    response = docker_post_with_http_status(docker2, url, "{\"Detach\":false,\"Tty\":false}", &http_status);
    
    ...

    return ???; // The buffer of docker2 is empty.
}

我找到了这个功能的官方Python测试代码,这基本上就是我想要的。我还在终端中测试了 cURL 命令没有问题:

curl -H "Content-Type: application/json" -X POST http://localhost:2375/containers/[container_id]/exec -d '{ "AttachStdout": true, "AttachStderr": true, "Cmd": ["ls", "-l", "/"] }'
curl -H "Content-Type: application/json" -X POST http://localhost:2375/exec/[exec_id]/start -d '{"Detach": false, "Tty": false}' --output -

并尝试修改 libdocker 但没有成功:

curl_easy_setopt(client->curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(client->curl, CURLOPT_WRITEDATA, docker_buffer(client));

启动exec的Docker实例缓冲区总是空的

c docker docker-exec
© www.soinside.com 2019 - 2024. All rights reserved.