如何使用python docker API在启用TLS的docker中写入stdin?

时间:2017-10-02 07:30:06

标签: docker

我使用python API使用基于TLS的docker。

我想写入标准输入(stdin),类似于:

echo ls | docker run --rm -i gliderlabs/alpine sh

怎么做?

1 个答案:

答案 0 :(得分:0)

必须获取底层套接字,并按如下方式调用适当的方法sendallrecv

# one needs to start the container first, and it is not possible to start the shell directly
# because methoed "run" does not support returning a socket
# one also needs to detach it otherwise the container waits synchronously for the end of the command
# calling "sleep" works, it is actually good because it means that the container will timeout if something goes bad
container = client.containers.run("gliderlabs/alpine", command= "sleep 100", detach = True)
# now we call the shell
# note that we don't set tty=True otherwise one gets the shell invite
socket = container.exec_run(cmd="sh", stdin=True, socket = True)
# we set the timeout in order not to be blocked afterwards with blocking read
socket.socket.settimeout(1)
# note that os.write does not work
# because it does not TLS-encrypt
# one must use "sendall" instead
socket.sendall(b"ls\n")

# a read block after a send
try:
    unknown_byte=socket.recv(1)
    while 1:
        # note that os.read does not work
        # because it does not TLS-decrypt
        # but returns the low-level encrypted data
        # one must use "socket.recv" instead
        data = socket.recv(16384)
        if not data: break
        print(data.decode('utf8'))
except so.timeout: pass

socket.sendall(b"exit\n")