2019-04-17 09:46
浏览 691

通过Docker API在正在运行的容器中执行powershell命令

I want to execute a powershell command in a docker container running on a windows host.

The specific command I want to execute is "powershell Get-PSDrive C | Select-Object Used,Free"

I have implemented this using the Docker API for python and it is simple like calling:

cmd = "powershell Get-PSDrive C | Select-Object Used,Free"
output = container.exec_run(cmd)

This works as intended, but I need to implement this in golang.

But somehow, it is not clear for me how to interact with the Docker API for golang. I looked into the API and was confused by the hijackedSession. How do I have to setup the calls for ContainerExecCreate, ContainerExecAttach and ContainerExecStart ?

I expect the golang script to deliver the same results like the python code does:

        Used         Free
        ----         ----
199181606912 307151622144

Which then can be parsed by me.

图片转代码服务由CSDN问答提供 功能建议

我想在Windows主机上运行的Docker容器中执行powershell命令。 \ n

我要执行的特定命令是“ powershell Get-PSDrive C |使用的选择对象,免费”

我已经使用 用于python的Docker API,它很简单,例如调用:

  cmd =“ powershell Get-PSDrive C |使用的选择对象,免费” 
output = container.exec_run(cmd)  


但是,目前尚不清楚 我如何与用于golang的Docker API交互。 我查看了API,并对 hijackedSession 感到困惑。 我应该如何设置对 ContainerExecCreate ContainerExecAttach ContainerExecStart 的调用?

我希望 golang脚本可提供与python代码相同的结果:

 ---- ---- 
199181606912 307151622144 


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doupang3062 2019-04-21 15:03

    The HijackedResponse struct:

    type HijackedResponse struct {
        Conn   net.Conn
        Reader *bufio.Reader

    You need to copy the response from the resp.Reader,here is my code:

    package main
    import (
    func readFromCommand() (string, error) {
        cli, err := client.NewEnvClient()
        if err != nil {
            return "", err
        ctx := context.Background()
        config := types.ExecConfig{
            Cmd:          strings.Split("powershell Get-PSDrive C | Select-Object Used,Free", " "),
            AttachStdout: true,
            AttachStderr: true,
        response, err := cli.ContainerExecCreate(ctx,
            // container id
            "cf59d65ab1", config)
        if err != nil {
            return "", err
        execID := response.ID
        resp, err := cli.ContainerExecAttach(ctx, execID, config)
        if err != nil {
            return "", err
        defer resp.Close()
        stdout := new(bytes.Buffer)
        stderr := new(bytes.Buffer)
        _, err = stdcopy.StdCopy(stdout, stderr, resp.Reader)
        if err != nil {
            return "", err
        s := stdout.String()
        i := stderr.String()
        return s, nil

    Do remember to change the container id.

    打赏 评论

相关推荐 更多相似问题