|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import ntpath |
| 4 | +import os |
| 5 | +from pathlib import PurePath |
| 6 | +from shlex import quote |
| 7 | +from socket import timeout as SocketTimeoutError |
| 8 | +from typing import IO, AnyStr |
| 9 | + |
| 10 | +from paramiko import Channel |
| 11 | +from paramiko.transport import Transport |
| 12 | + |
| 13 | +SCP_COMMAND = b"scp" |
| 14 | + |
| 15 | + |
| 16 | +# Unicode conversion functions; assume UTF-8 |
| 17 | +def asbytes(s: bytes | str | PurePath) -> bytes: |
| 18 | + """Turns unicode into bytes, if needed. |
| 19 | +
|
| 20 | + Assumes UTF-8. |
| 21 | + """ |
| 22 | + if isinstance(s, bytes): |
| 23 | + return s |
| 24 | + elif isinstance(s, PurePath): |
| 25 | + return bytes(s) |
| 26 | + else: |
| 27 | + return s.encode("utf-8") |
| 28 | + |
| 29 | + |
| 30 | +def asunicode(s: bytes | str) -> str: |
| 31 | + """Turns bytes into unicode, if needed. |
| 32 | +
|
| 33 | + Uses UTF-8. |
| 34 | + """ |
| 35 | + if isinstance(s, bytes): |
| 36 | + return s.decode("utf-8", "replace") |
| 37 | + else: |
| 38 | + return s |
| 39 | + |
| 40 | + |
| 41 | +class SCPClient: |
| 42 | + """ |
| 43 | + An scp1 implementation, compatible with openssh scp. |
| 44 | + Raises SCPException for all transport related errors. Local filesystem |
| 45 | + and OS errors pass through. |
| 46 | +
|
| 47 | + Main public methods are .putfo and .getfo |
| 48 | + """ |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + transport: Transport, |
| 53 | + buff_size: int = 16384, |
| 54 | + socket_timeout: float = 10.0, |
| 55 | + ): |
| 56 | + self.transport = transport |
| 57 | + self.buff_size = buff_size |
| 58 | + self.socket_timeout = socket_timeout |
| 59 | + self._channel: Channel | None = None |
| 60 | + self.scp_command = SCP_COMMAND |
| 61 | + |
| 62 | + @property |
| 63 | + def channel(self) -> Channel: |
| 64 | + """Return an open Channel, (re)opening if needed.""" |
| 65 | + if self._channel is None or self._channel.closed: |
| 66 | + self._channel = self.transport.open_session() |
| 67 | + return self._channel |
| 68 | + |
| 69 | + def __enter__(self): |
| 70 | + _ = self.channel # triggers opening if not already open |
| 71 | + return self |
| 72 | + |
| 73 | + def __exit__(self, type, value, traceback): |
| 74 | + self.close() |
| 75 | + |
| 76 | + def putfo( |
| 77 | + self, |
| 78 | + fl: IO[AnyStr], |
| 79 | + remote_path: str | bytes, |
| 80 | + mode: str | bytes = "0644", |
| 81 | + size: int | None = None, |
| 82 | + ) -> None: |
| 83 | + if size is None: |
| 84 | + pos = fl.tell() |
| 85 | + fl.seek(0, os.SEEK_END) # Seek to end |
| 86 | + size = fl.tell() - pos |
| 87 | + fl.seek(pos, os.SEEK_SET) # Seek back |
| 88 | + |
| 89 | + self.channel.settimeout(self.socket_timeout) |
| 90 | + self.channel.exec_command( |
| 91 | + self.scp_command + b" -t " + asbytes(quote(asunicode(remote_path))) |
| 92 | + ) |
| 93 | + self._recv_confirm() |
| 94 | + self._send_file(fl, remote_path, mode, size=size) |
| 95 | + self.close() |
| 96 | + |
| 97 | + def getfo(self, remote_path: str, fl: IO): |
| 98 | + remote_path_sanitized = quote(remote_path) |
| 99 | + if os.name == "nt": |
| 100 | + remote_file_name = ntpath.basename(remote_path_sanitized) |
| 101 | + else: |
| 102 | + remote_file_name = os.path.basename(remote_path_sanitized) |
| 103 | + self.channel.settimeout(self.socket_timeout) |
| 104 | + self.channel.exec_command(self.scp_command + b" -f " + asbytes(remote_path_sanitized)) |
| 105 | + self._recv_all(fl, remote_file_name) |
| 106 | + self.close() |
| 107 | + return fl |
| 108 | + |
| 109 | + def close(self): |
| 110 | + """close scp channel""" |
| 111 | + if self._channel is not None: |
| 112 | + self._channel.close() |
| 113 | + self._channel = None |
| 114 | + |
| 115 | + def _send_file(self, fl, name, mode, size): |
| 116 | + basename = asbytes(os.path.basename(name)) |
| 117 | + # The protocol can't handle \n in the filename. |
| 118 | + # Quote them as the control sequence \^J for now, |
| 119 | + # which is how openssh handles it. |
| 120 | + self.channel.sendall( |
| 121 | + ("C%s %d " % (mode, size)).encode("ascii") + basename.replace(b"\n", b"\\^J") + b"\n" |
| 122 | + ) |
| 123 | + self._recv_confirm() |
| 124 | + file_pos = 0 |
| 125 | + buff_size = self.buff_size |
| 126 | + chan = self.channel |
| 127 | + while file_pos < size: |
| 128 | + chan.sendall(fl.read(buff_size)) |
| 129 | + file_pos = fl.tell() |
| 130 | + chan.sendall(b"\x00") |
| 131 | + self._recv_confirm() |
| 132 | + |
| 133 | + def _recv_confirm(self): |
| 134 | + # read scp response |
| 135 | + msg = b"" |
| 136 | + try: |
| 137 | + msg = self.channel.recv(512) |
| 138 | + except SocketTimeoutError: |
| 139 | + raise SCPException("Timeout waiting for scp response") |
| 140 | + # slice off the first byte, so this compare will work in py2 and py3 |
| 141 | + if msg and msg[0:1] == b"\x00": |
| 142 | + return |
| 143 | + elif msg and msg[0:1] == b"\x01": |
| 144 | + raise SCPException(asunicode(msg[1:])) |
| 145 | + elif self.channel.recv_stderr_ready(): |
| 146 | + msg = self.channel.recv_stderr(512) |
| 147 | + raise SCPException(asunicode(msg)) |
| 148 | + elif not msg: |
| 149 | + raise SCPException("No response from server") |
| 150 | + else: |
| 151 | + raise SCPException("Invalid response from server", msg) |
| 152 | + |
| 153 | + def _recv_all(self, fh: IO, remote_file_name: str) -> None: |
| 154 | + # loop over scp commands, and receive as necessary |
| 155 | + commands = (b"C",) |
| 156 | + while not self.channel.closed: |
| 157 | + # wait for command as long as we're open |
| 158 | + self.channel.sendall(b"\x00") |
| 159 | + msg = self.channel.recv(1024) |
| 160 | + if not msg: # chan closed while receiving |
| 161 | + break |
| 162 | + assert msg[-1:] == b"\n" |
| 163 | + msg = msg[:-1] |
| 164 | + code = msg[0:1] |
| 165 | + if code not in commands: |
| 166 | + raise SCPException(asunicode(msg[1:])) |
| 167 | + self._recv_file(msg[1:], fh, remote_file_name) |
| 168 | + |
| 169 | + def _recv_file(self, cmd: bytes, fh: IO, remote_file_name: str) -> None: |
| 170 | + chan = self.channel |
| 171 | + parts = cmd.strip().split(b" ", 2) |
| 172 | + |
| 173 | + try: |
| 174 | + size = int(parts[1]) |
| 175 | + except (ValueError, IndexError): |
| 176 | + chan.send(b"\x01") |
| 177 | + chan.close() |
| 178 | + raise SCPException("Bad file format") |
| 179 | + |
| 180 | + buff_size = self.buff_size |
| 181 | + pos = 0 |
| 182 | + chan.send(b"\x00") |
| 183 | + try: |
| 184 | + while pos < size: |
| 185 | + # we have to make sure we don't read the final byte |
| 186 | + if size - pos <= buff_size: |
| 187 | + buff_size = size - pos |
| 188 | + data = chan.recv(buff_size) |
| 189 | + if not data: |
| 190 | + raise SCPException("Underlying channel was closed") |
| 191 | + fh.write(data) |
| 192 | + pos = fh.tell() |
| 193 | + msg = chan.recv(512) |
| 194 | + if msg and msg[0:1] != b"\x00": |
| 195 | + raise SCPException(asunicode(msg[1:])) |
| 196 | + except SocketTimeoutError: |
| 197 | + chan.close() |
| 198 | + raise SCPException("Error receiving, socket.timeout") |
| 199 | + |
| 200 | + |
| 201 | +class SCPException(Exception): |
| 202 | + """SCP exception class""" |
| 203 | + |
| 204 | + pass |
0 commit comments