简体   繁体   English

如何使用 docker-py 将伪 tty 附加到 Docker 容器以复制 `docker exec -ti 的行为<container><command> `?</container>

[英]How to attach a pseudo-tty to a Docker container with docker-py to replicate behaviour of `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.我正在使用最新版本的 Docker Py 并且我无法将伪 tty 附加到已经运行的容器,以确保复制docker exec -ti <container> <command>的行为。 Any help would be appreciated.任何帮助,将不胜感激。

Try using attach method or attach-stream from the docker-py.尝试使用 docker-py 中的attach方法或attach-stream

As described in docker-py attach , the method is attaching tty(s) to the running container.如 docker-py attach中所述,该方法是将 tty(s) 附加到正在运行的容器。 This is similar to the native docker attach command which is attaching the stdin, stdout and stderr to the container.这类似于将标准输入、标准输出和标准错误附加到容器的原生docker attach命令

The container needs to be created with stdin_open = True and tty = true when calling create_container for the attach to work.在调用create_container以使attach工作时,需要使用stdin_open = Truetty = true创建容器。

Example using attach-socket :使用attach-socket示例:

pull the debian:latest containerdebian:latest容器

docker pull debian:latest

Create the python script test.py as follows创建python脚本test.py如下

#! 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)

Now test the script.现在测试脚本。 You will see the output from the command we had executed at the shell.您将从我们在 shell 执行的命令中看到 output。

~# 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# '

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.这种方法特定于用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM