如何使用docker-py将伪tty附加到Docker容器以复制docker exec -ti< container>的行为.< command>`? [英] How to attach a pseudo-tty to a Docker container with docker-py to replicate behaviour of `docker exec -ti <container> <command>`?

查看:69
本文介绍了如何使用docker-py将伪tty附加到Docker容器以复制docker exec -ti< container>的行为.< command>`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新版本的Docker Py,但无法将伪tty附加到已运行的容器上,以确保 docker exec -ti< container>的行为是否正常.< command> 被复制.任何帮助将不胜感激.

I am using the most recent version of Docker Py and I have not been able to attach a pseudo-tty to an already running container so as to make sure that the behaviour of docker exec -ti <container> <command> is replicated. Any help would be appreciated.

推荐答案

尝试使用docker-py中的 attach 方法或 attach-stream .

Try using attach method or attach-stream from the docker-py.

如docker-py attach ,该方法会将tty连接到正在运行的容器.这类似于本地人 docker attach 命令,它会附加标准输入,stdout和stderr移至容器.

As described in docker-py attach, the method is attaching tty(s) to the running container. This is similar to the native docker attach command which is attaching the stdin, stdout and stderr to the container.

调用 create_container 进行附加时,需要使用 stdin_open = True tty = true 创建容器>上班.

The container needs to be created with stdin_open = True and tty = true when calling create_container for the attach to work.

使用 attach-socket 的示例:

拉出 debian:latest 容器

docker pull debian:latest

按如下所示创建python脚本 test.py

Create the python script test.py as follows

#! python3
import docker
import os
import time

# Create container and start it
client = docker.from_env()
container = client.create_container('debian:latest', name='test', stdin_open = True, tty = True, command = 'sh')
client.start(container)

# Create communication socket
s = client.attach_socket(container, {'stdin': 1, 'stdout': 1, 'stream':1})

# Set the socket as non-blocking
s._sock.setblocking(False)

# Start communication by sending cat
os.write(s.fileno(),b'cat /etc/hosts\n')

# Since we are non-blocking, wait for a while to get the output
time.sleep(1)

# Read up-to 10000 bytes. If there are more, we can issue another read
print(os.read(s.fileno(),10000))

client.stop(container)
client.wait(container)
client.remove_container(container)

现在测试脚本.您将看到我们已经在shell中执行的命令的输出.

Now test the script. You will see the output from the command we had executed at the shell.

~# python3 test.py
b'cat /etc/hosts\r\n127.0.0.1\tlocalhost\r\n::1\tlocalhost ip6-localhost ip6-loopback\r\nfe00::0\tip6-localnet\r\nff00::0\tip6-mcastprefix\r\nff02::1\tip6-allnodes\r\nff02::2\tip6-allrouters\r\n172.17.0.2\t48f4a5f32f48\r\n# '

注意:套接字被设置为non-blockin,以避免在等待容器响应时被阻塞.这种方法特定于用例.

Note: The socket is set to non-blockin in order to avoid being blocked while waiting for the response from the container. This approach is specific to the use case.

这篇关于如何使用docker-py将伪tty附加到Docker容器以复制docker exec -ti&lt; container&gt;的行为.&lt; command&gt;`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆