Skip to content

Commit

Permalink
Improved ssh config support in Paramiko backend
Browse files Browse the repository at this point in the history
The include statement is now supported when using paramiko as the
backend
  • Loading branch information
tpmullan authored and philpep committed Nov 5, 2022
1 parent 30acc8a commit aae13bd
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions testinfra/backend/paramiko.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def __init__(
self.timeout = int(timeout)
super().__init__(self.host.name, *args, **kwargs)

def _load_ssh_config(self, client, cfg, ssh_config):
def _load_ssh_config(self, client, cfg, ssh_config, ssh_config_dir="~/.ssh"):
for key, value in ssh_config.lookup(self.host.name).items():
if key == "hostname":
cfg[key] = value
Expand All @@ -74,6 +74,14 @@ def _load_ssh_config(self, client, cfg, ssh_config):
cfg["gss_kex"] = value == "yes"
elif key == "proxycommand":
cfg["sock"] = paramiko.ProxyCommand(value)
elif key == "include":
new_config_path = os.path.join(
os.path.expanduser(ssh_config_dir), value
)
with open(new_config_path) as f:
new_ssh_config = paramiko.SSHConfig()
new_ssh_config.parse(f)
self._load_ssh_config(client, cfg, new_ssh_config, ssh_config_dir)

@cached_property
def client(self):
Expand All @@ -87,21 +95,25 @@ def client(self):
"password": self.host.password,
}
if self.ssh_config:
ssh_config_dir = os.path.dirname(self.ssh_config)

with open(self.ssh_config) as f:
ssh_config = paramiko.SSHConfig()
ssh_config.parse(f)
self._load_ssh_config(client, cfg, ssh_config)
self._load_ssh_config(client, cfg, ssh_config, ssh_config_dir)
else:
# fallback reading ~/.ssh/config
default_ssh_config = os.path.join(os.path.expanduser("~"), ".ssh", "config")
ssh_config_dir = os.path.dirname(default_ssh_config)

try:
with open(default_ssh_config) as f:
ssh_config = paramiko.SSHConfig()
ssh_config.parse(f)
except IOError:
pass
else:
self._load_ssh_config(client, cfg, ssh_config)
self._load_ssh_config(client, cfg, ssh_config, ssh_config_dir)

if self.ssh_identity_file:
cfg["key_filename"] = self.ssh_identity_file
Expand Down

0 comments on commit aae13bd

Please sign in to comment.