<p>I need to copy a file from a pod to the host by using kubernetes python client. It would be something like <code>kubectl cp pod:file file</code>.</p>

<p>I'm testing the code from: <a href="https://github.com/prafull01/Kubernetes-Utilities/blob/master/kubectl_cp_as_python_client.py" rel="noreferrer">https://github.com/prafull01/Kubernetes-Utilities/blob/master/kubectl_cp_as_python_client.py</a>.</p>

<p>Specifically this code:</p>

<pre class="lang-py prettyprint-override"><code>command_copy = ['tar', 'cf', '-', source_path]
with TemporaryFile() as tar_buffer:
    exec_stream = stream(self.coreClient.connect_get_namespaced_pod_exec, pod_name, name_space,
                         command=command_copy, stderr=True, stdin=True, stdout=True, tty=False,
                         _preload_content=False)
    # Copy file to stream

    try:
        while exec_stream.is_open():
            exec_stream.update(timeout=1)
            if exec_stream.peek_stdout():
                out = exec_stream.read_stdout()
                tar_buffer.write(out.encode('utf-8'))
            if exec_stream.peek_stderr():
                logger.debug("STDERR: %s" % exec_stream.read_stderr())
        exec_stream.close()
        tar_buffer.flush()
        tar_buffer.seek(0)
        with tarfile.open(fileobj=tar_buffer, mode='r:') as tar:
            member = tar.getmember(source_path)
            tar.makefile(member, destination_path)
            return True
    except Exception as e:
        raise manage_kubernetes_exception(e)
</code></pre>

<p>I'm using the oficial Kubernetes Python library version 10.0.1 stable with Python 3.6.8</p>

<p>But it is not working properly:</p>

<ul>
<li>It is working when I copy small text files</li>
<li>but it is not working for other files such as a tar or zip file. It copies a corrupted file with same size that the original. </li>
</ul>

<p>Is there any mistake in the code? Do you have any other way to do it by using kubernetes python client?</p>

<p>All the best.</p>

<p>Thanks.</p>

<p>I did it by using the following code:</p>
<pre><code>def stream_copy_from_pod(self, pod_name, name_space, source_path, destination_path):
    &quot;&quot;&quot;
    Copy file from pod to the host.

    :param pod_name: String. Pod name
    :param name_space: String. Namespace
    :param source_path: String. Pod destination file path
    :param destination_path: Host destination file path
    :return: bool
    &quot;&quot;&quot;
    command_copy = ['tar', 'cf', '-', source_path]
    with TemporaryFile() as tar_buffer:
        exec_stream = stream(self.coreClient.connect_get_namespaced_pod_exec, pod_name, name_space,
                             command=command_copy, stderr=True, stdin=True, stdout=True, tty=False,
                             _preload_content=False)
        # Copy file to stream
        try:
            reader = WSFileManager(exec_stream)
            while True:
                out, err, closed = reader.read_bytes()
                if out:
                    tar_buffer.write(out)
                elif err:
                    logger.debug(&quot;Error copying file {0}&quot;.format(err.decode(&quot;utf-8&quot;, &quot;replace&quot;)))
                if closed:
                    break
            exec_stream.close()
            tar_buffer.flush()
            tar_buffer.seek(0)
            with tarfile.open(fileobj=tar_buffer, mode='r:') as tar:
                member = tar.getmember(source_path)
                tar.makefile(member, destination_path)
                return True
        except Exception as e:
            raise manage_kubernetes_exception(e)
</code></pre>
<p>Using this web socket file manager for read it.</p>
<pre><code>class WSFileManager:
&quot;&quot;&quot;
WS wrapper to manage read and write bytes in K8s WSClient
&quot;&quot;&quot;

def __init__(self, ws_client):
    &quot;&quot;&quot;

    :param wsclient: Kubernetes WSClient
    &quot;&quot;&quot;
    self.ws_client = ws_client

def read_bytes(self, timeout=0):
    &quot;&quot;&quot;
    Read slice of bytes from stream

    :param timeout: read timeout
    :return: stdout, stderr and closed stream flag
    &quot;&quot;&quot;
    stdout_bytes = None
    stderr_bytes = None

    if self.ws_client.is_open():
        if not self.ws_client.sock.connected:
            self.ws_client._connected = False
        else:
            r, _, _ = select.select(
                (self.ws_client.sock.sock, ), (), (), timeout)
            if r:
                op_code, frame = self.ws_client.sock.recv_data_frame(True)
                if op_code == ABNF.OPCODE_CLOSE:
                    self.ws_client._connected = False
                elif op_code == ABNF.OPCODE_BINARY or op_code == ABNF.OPCODE_TEXT:
                    data = frame.data
                    if len(data) &gt; 1:
                        channel = data[0]
                        data = data[1:]
                        if data:
                            if channel == STDOUT_CHANNEL:
                                stdout_bytes = data
                            elif channel == STDERR_CHANNEL:
                                stderr_bytes = data
    return stdout_bytes, stderr_bytes, not self.ws_client._connected
</code></pre>
