Skip to content

Commit

Permalink
sftp: add support for ~/.ssh/config, fixes #37
Browse files Browse the repository at this point in the history
including support for configured IdentityFiles
  • Loading branch information
ThomasWaldmann committed Sep 16, 2024
1 parent 90b4363 commit 330e026
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
15 changes: 14 additions & 1 deletion src/borgstore/backends/sftp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
20 changes: 15 additions & 5 deletions tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down

0 comments on commit 330e026

Please sign in to comment.