使用Golang访问交互式shell中的docker容器



我正在尝试使用Golang访问正在运行的docker容器的交互式shell。这是我试过的。

package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func main() {
prg := "docker"
arg1 := "exec"
arg2 := "-ti"
arg3 := "df43f9a0d5c4"
arg4 := "bash"
cmd := exec.Command(prg, arg1, arg2, arg3, arg4)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
fmt.Printf("[Command] %sn", cmd.String())
log.Printf("Running command and waiting for it to finish...")
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Command finished with error %sn", cmd.String())

}

AND这里是带错误的输出:

> [Command] /usr/bin/docker exec -ti df43f9a0d5c4 bash 2022/07/28
> 19:21:02 Running command and waiting for it to finish... the input
> device is not a TTY 2022/07/28 19:21:02 exit status 1 exit status 1

Note: Interactive shell of running docker container works fine when executing this command directly on the shell

您正在传递-t,告诉docker exec为容器内的exec会话分配一个伪终端。

但是您没有将cmd.Stdin设置为任何值,所以cmd.Stdin就是nil。文件显示

//如果Stdin为零,则进程从零设备(os.DevNull(读取。

输入不是终端,所以这就是您获得的原因

输入设备不是TTY

你说

注意:当直接在shell 上执行此命令时,运行docker容器的交互式shell工作良好

因为当您直接在shell中运行它时,标准输入终端。

试试这个:

cmd.Stdin = os.Stdin

最新更新