douhao123457 2014-10-16 18:40
浏览 737

使用golang exec执行docker命令失败

I am using cmd.go (see below) to execute a docker command but it fails. I do the following steps to execute and get the following error.

go build
sudo ./cmd

Output:

docker run -v ~/exp/a.out:/a.out ubuntu:14.04 /a.out -m 10m
2014/10/16 14:32:12 exit status 1

On the other hand running directly as

sudo docker run -v ~/exp/a.out:/a.out ubuntu:14.04 /a.out -m 10m

results in the correct output of a.out.

Hello World

This is the code of cmd.go. How can I get it to work? Thanks!

package main

import (
        "fmt"
        "log"
        "os/exec"
        "strings"
)

func ExampleCmd_Output() {
        //out, err := exec.Command("date", "--version").Output()   // This works
        //out, err := exec.Command("docker", "--version").Output() // This works
        //out, err := exec.Command(cmd, "images").Output() // Even docker images command works!

        cmd := "docker"
        cmdArgs := []string{"run", "-v", "~/exp/a.out:/a.out", "ubuntu:14.04", "/a.out", "-m", "10m"}
        fmt.Println(cmd + " " + strings.Join(cmdArgs, " "))
        out, err := exec.Command(cmd, cmdArgs...).Output()
        if err != nil {
                log.Fatal(err)
        }
        fmt.Printf("%s", out)
}

func main() {
        ExampleCmd_Output()
}

EDIT: After a comment, I tried executing the command "docker images". It works if I run the executable with sudo. That is, I am using the following line in the code now.

out, err := exec.Command(cmd, "images").Output()

After doing go build and running "sudo ./cmd", I get the output of docker images command. However, without sudo, I still get exit status 1. But with docker run command above even with sudo, I don't get an output.

  • 写回答

1条回答 默认 最新

  • doubi1910 2014-10-17 00:11
    关注

    Thanks to Os Exec Sudo Command in Go, I am now able to do what I want.

    func main() {
      cmdStr := "sudo docker run -v ~/exp/a.out:/a.out ubuntu:14.04 /a.out -m 10m"
      out, _ := exec.Command("/bin/sh", "-c", cmdStr).Output()  
      fmt.Printf("%s", out)
    }
    

    Output:

    Hello World
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?