From 330e026507fd2a42cfd4e02927752721d6868db3 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Sun, 15 Sep 2024 10:56:31 +0200 Subject: [PATCH] sftp: add support for ~/.ssh/config, fixes #37 including support for configured IdentityFiles --- pyproject.toml | 2 +- src/borgstore/backends/sftp.py | 15 ++++++++++++++- tests/test_backends.py | 20 +++++++++++++++----- 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 1daaf02..2f187d2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ license = {text="BSD"} requires-python = ">=3.9" dependencies = [ - "paramiko", + "paramiko >= 1.9.1", # 1.9.1+ supports multiple IdentityKey entries in .ssh/config ] [project.urls] diff --git a/src/borgstore/backends/sftp.py b/src/borgstore/backends/sftp.py index 1d25e0c..719e77f 100644 --- a/src/borgstore/backends/sftp.py +++ b/src/borgstore/backends/sftp.py @@ -40,7 +40,20 @@ def __init__(self, hostname: str, path: str, port: int = 22, username: Optional[ def _connect(self): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - ssh.connect(hostname=self.hostname, username=self.username, port=self.port, allow_agent=True) + config_path = Path("~/.ssh/config").expanduser() + try: + sc = paramiko.SSHConfig.from_path(str(config_path)) + except FileNotFoundError: + scd = paramiko.SSHConfigDict() # empty dict + else: + scd = sc.lookup(self.hostname) + ssh.connect( + hostname=scd.get("hostname", self.hostname), + username=scd.get("user", self.username), + port=scd.as_int("port") if "port" in scd else self.port, + key_filename=scd.get("identityfile", None), # list of keys + allow_agent=True, + ) self.client = ssh.open_sftp() def _disconnect(self): diff --git a/tests/test_backends.py b/tests/test_backends.py index 7a15ed4..b0e0136 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -31,13 +31,23 @@ def posixfs_backend_created(tmp_path): be.destroy() -def _get_sftp_backend(): +def _get_sftp_backend(local=False, remote_url=False, remote_config=True): # needs an authorized key loaded into the ssh agent. pytest works, tox doesn't: - # return Sftp(username="tw", hostname="localhost", path="/Users/tw/w/borgstore/temp-store") + if local: + return Sftp(username="tw", hostname="localhost", path="/Users/tw/w/borgstore/temp-store") # for tests with higher latency: - return Sftp( - username="twaldmann", hostname="shell.ipv4.thinkmo.de", port=2222, path="/home/twaldmann/borgstore/temp-store" - ) + if remote_url: + return Sftp( + username="twaldmann", + hostname="shell.ipv4.thinkmo.de", + port=2222, + path="/home/twaldmann/borgstore/temp-store", + ) + # same as previous, but loads config for host "shell" from ~/.ssh/config: + if remote_config: + return Sftp(hostname="shell", path="/home/twaldmann/borgstore/temp-store") + + raise ValueError("check _get_sftp_backend() parameter defaults!") def check_sftp_available():