Skip to content

Подключение к SFTP

Bases: FileConnection, RenameDirMixin

SFTP file connection. support hooks

Based on Paramiko library.

Warning

Since onETL v0.7.0 to use SFTP connector you should install package as follows:

pip install "onetl[sftp]"

# or
pip install "onetl[files]"
See [install-files][] installation instruction for more details.

Added in 0.1.0

Parameters

host : str Host of SFTP source. For example: 192.168.1.19

int, default: 22

Port of SFTP source

str

User, which have access to the file source. For example: someuser

str, optional.

Password for SFTP connection, optional.

str, optional.

Path to private key file, optional.

SFTPExtra, default: SFTPExtra()

Extra options for SFTP connection

Examples

from onetl.connection import SFTP

sftp = SFTP(
    host="192.168.1.19",
    user="someuser",
    password="*****",
).check()
from onetl.connection import SFTP

sftp = SFTP(
    host="192.168.1.19",
    user="someuser",
    key_file="~/.ssh/id_rsa",
).check()
from onetl.connection import SFTP

sftp = SFTP(
    host="192.168.1.19",
    user="someuser",
    password="*****",
    extra=SFTP.Extra(host_key_check=True, timeout=60),
).check()
Source code in onetl/connection/file_connection/sftp.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
@support_hooks
class SFTP(FileConnection, RenameDirMixin):
    """SFTP file connection. [![support hooks](https://img.shields.io/badge/%20-support%20hooks-blue)](/hooks/)

    Based on [Paramiko library](https://pypi.org/project/paramiko/).

    !!! warning

        Since onETL v0.7.0 to use SFTP connector you should install package as follows:

        ```bash
        pip install "onetl[sftp]"

        # or
        pip install "onetl[files]"
        ```
        See [install-files][] installation instruction for more details.

    !!! success "Added in 0.1.0"

    Parameters
    ----------
    host : str
        Host of SFTP source. For example: `192.168.1.19`

    port : int, default: `22`
        Port of SFTP source

    user : str
        User, which have access to the file source. For example: `someuser`

    password : str, optional.
        Password for SFTP connection, optional.

    key_file : str, optional.
        Path to private key file, optional.

    extra : SFTPExtra, default: `SFTPExtra()`
        Extra options for SFTP connection

    Examples
    --------

    === "Create SFTP connection with password"

        ```python
        from onetl.connection import SFTP

        sftp = SFTP(
            host="192.168.1.19",
            user="someuser",
            password="*****",
        ).check()
        ```

    === "Create SFTP connection with private key file"

        ```python
        from onetl.connection import SFTP

        sftp = SFTP(
            host="192.168.1.19",
            user="someuser",
            key_file="~/.ssh/id_rsa",
        ).check()
        ```

    === "Create SFTP connection with extra options"

        ```python
        from onetl.connection import SFTP

        sftp = SFTP(
            host="192.168.1.19",
            user="someuser",
            password="*****",
            extra=SFTP.Extra(host_key_check=True, timeout=60),
        ).check()
        ```
    """

    host: Host
    port: int = 22
    user: Optional[str] = None
    password: Optional[SecretStr] = None
    key_file: Optional[FilePath] = None
    extra: SFTPExtra = Field(default_factory=SFTPExtra)

    Extra = SFTPExtra

    @root_validator(pre=True)
    def _extra_fallback(cls, values):
        extra_dict = cls.Extra.parse(values.get("extra")).dict(exclude_unset=True, by_alias=True)
        for key in ["timeout", "host_key_check", "compress"]:
            if key not in values:
                continue

            value = values.pop(key)
            warnings.warn(
                f"Option `{key}` is deprecated since v0.16.0 and will be removed in v1.0.0. "
                f"Use extra={cls.__name__}.Extra({key}={value!r}) instead",
                category=UserWarning,
                stacklevel=5,
            )
            extra_dict[key] = value
        values["extra"] = cls.Extra.parse(extra_dict)
        return values

    @property
    def instance_url(self) -> str:
        return f"{self.__class__.__name__.lower()}://{self.host}:{self.port}"

    def __str__(self):
        return f"{self.__class__.__name__}[{self.host}:{self.port}]"

    @slot
    def path_exists(self, path: os.PathLike | str) -> bool:
        try:
            self.client.stat(os.fspath(path))
        except FileNotFoundError:
            return False
        else:
            return True

    def _get_client(self) -> SFTPClient:
        host_proxy, key_file = self._parse_user_ssh_config()

        client = SSHClient()
        client.load_system_host_keys()
        if not self.extra.host_key_check:
            # Default is RejectPolicy
            client.set_missing_host_key_policy(WarningPolicy())  # noqa: S507

        extra = self.extra.dict(by_alias=True, exclude={"host_key_check"})
        client.connect(
            hostname=self.host,
            port=self.port,
            username=self.user,
            password=self.password.get_secret_value() if self.password else None,
            key_filename=key_file,
            sock=host_proxy,
            **extra,
        )

        return client.open_sftp()

    def _is_client_closed(self, client: SFTPClient) -> bool:
        return not client.sock or client.sock.closed

    def _close_client(self, client: SFTPClient) -> None:
        client.close()

    def _parse_user_ssh_config(self) -> tuple[ProxyCommand | None, str | None]:
        host_proxy = None
        key_file = os.fspath(self.key_file) if self.key_file else None

        if not SSH_CONFIG_PATH.exists() or not SSH_CONFIG_PATH.is_file():
            return host_proxy, key_file

        try:
            ssh_conf = SSHConfig()
            ssh_conf.parse(SSH_CONFIG_PATH.read_text())
            host_info = ssh_conf.lookup(self.host) or {}

            proxycommand = host_info.get("proxycommand")
            if proxycommand:
                host_proxy = ProxyCommand(proxycommand)

            if not (self.password or key_file):
                identityfile = host_info.get("identityfile")
                if identityfile:
                    key_file = identityfile[0]
        except ConfigParseError:
            log.exception("Failed to parse SSH config")

        return host_proxy, key_file

    def _create_dir(self, path: RemotePath) -> None:
        try:
            self.client.stat(os.fspath(path))
        except OSError:
            for parent in reversed(path.parents):
                try:
                    self.client.stat(os.fspath(parent))
                except OSError:  # noqa: PERF203
                    self.client.mkdir(os.fspath(parent))

            self.client.mkdir(os.fspath(path))

    def _upload_file(self, local_file_path: RemotePath, remote_file_path: RemotePath) -> None:
        self.client.put(os.fspath(local_file_path), os.fspath(remote_file_path))

    def _rename_file(self, source: RemotePath, target: RemotePath) -> None:
        with contextlib.suppress(OSError):
            self.client.posix_rename(os.fspath(source), os.fspath(target))
            return

        # posix rename extension is not supported by server
        # if OSError was caused by permissions error, client.rename will raise this exception again
        self.client.rename(os.fspath(source), os.fspath(target))

    _rename_dir = _rename_file

    def _download_file(self, remote_file_path: RemotePath, local_file_path: RemotePath) -> None:
        self.client.get(os.fspath(remote_file_path), os.fspath(local_file_path))

    def _remove_dir(self, path: RemotePath) -> None:
        self.client.rmdir(os.fspath(path))

    def _remove_file(self, remote_file_path: RemotePath) -> None:
        self.client.remove(os.fspath(remote_file_path))

    def _scan_entries(self, path: RemotePath) -> list[SFTPAttributes]:
        return self.client.listdir_attr(os.fspath(path))

    def _is_dir(self, path: RemotePath) -> bool:
        stat: SFTPAttributes = self.client.stat(os.fspath(path))
        return S_ISDIR(stat.st_mode)

    def _is_file(self, path: RemotePath) -> bool:
        stat: SFTPAttributes = self.client.stat(os.fspath(path))
        return S_ISREG(stat.st_mode)

    def _get_stat(self, path: RemotePath) -> SFTPAttributes:
        # underlying SFTP client already return `os.stat_result`-like class
        return self.client.stat(os.fspath(path))

    def _extract_name_from_entry(self, entry: SFTPAttributes) -> str:
        return entry.filename  # type: ignore[attr-defined]

    def _is_dir_entry(self, top: RemotePath, entry: SFTPAttributes) -> bool:
        return S_ISDIR(entry.st_mode)

    def _is_file_entry(self, top: RemotePath, entry: SFTPAttributes) -> bool:
        return S_ISREG(entry.st_mode)

    def _extract_stat_from_entry(self, top: RemotePath, entry: SFTPAttributes) -> SFTPAttributes:
        return entry

    def _read_text(self, path: RemotePath, encoding: str, **kwargs) -> str:
        with self.client.open(os.fspath(path), mode="r", **kwargs) as file:
            return file.read().decode(encoding)

    def _read_bytes(self, path: RemotePath, **kwargs) -> bytes:
        with self.client.open(os.fspath(path), mode="r", **kwargs) as file:
            return file.read()

    def _write_text(self, path: RemotePath, content: str, encoding: str, **kwargs) -> None:
        with self.client.open(os.fspath(path), mode="w", **kwargs) as file:
            file.write(content.encode(encoding))

    def _write_bytes(self, path: RemotePath, content: bytes, **kwargs) -> None:
        with self.client.open(os.fspath(path), mode="w", **kwargs) as file:
            file.write(content)

path_exists(path)

Source code in onetl/connection/file_connection/sftp.py
204
205
206
207
208
209
210
211
@slot
def path_exists(self, path: os.PathLike | str) -> bool:
    try:
        self.client.stat(os.fspath(path))
    except FileNotFoundError:
        return False
    else:
        return True