diff --git a/devlib/utils/ssh.py b/devlib/utils/ssh.py index bc13022..7244a55 100644 --- a/devlib/utils/ssh.py +++ b/devlib/utils/ssh.py @@ -17,6 +17,7 @@ import os import stat import logging +from pathlib import Path import subprocess import re import threading @@ -174,6 +175,18 @@ def _read_paramiko_streams_internal(stdout, stderr, select_timeout, callback, in return (callback_state, exit_code) +def _resolve_known_hosts(strict_host_check): + if strict_host_check: + if isinstance(strict_host_check, (str, os.PathLike)): + path = Path(strict_host_check) + else: + path = Path('~/.ssh/known_hosts').expandvars() + else: + path = Path('/dev/null') + + return str(path.resolve()) + + def telnet_get_shell(host, username, password=None, @@ -407,7 +420,9 @@ class SshConnection(SshConnectionBase): with _handle_paramiko_exceptions(): client = SSHClient() if self.strict_host_check: - client.load_system_host_keys() + client.load_system_host_keys(_resolve_known_hosts( + self.strict_host_check + )) client.set_missing_host_key_policy(policy) client.connect( hostname=self.host, @@ -818,16 +833,12 @@ class TelnetConnection(SshConnectionBase): return '{}@{}:{}'.format(self.username, self.host, path) def _get_default_options(self): - if self.strict_host_check: - options = { - 'StrictHostKeyChecking': 'yes', - } - else: - options = { - 'StrictHostKeyChecking': 'no', - 'UserKnownHostsFile': '/dev/null', - } - return options + check = self.strict_host_check + known_hosts = _resolve_known_hosts(check) + return { + 'StrictHostKeyChecking': 'yes' if check else 'no', + 'UserKnownHostsFile': str(known_hosts), + } def push(self, sources, dest, timeout=30): # Quote the destination as SCP would apply globbing too diff --git a/doc/connection.rst b/doc/connection.rst index 58f1885..71ce155 100644 --- a/doc/connection.rst +++ b/doc/connection.rst @@ -177,7 +177,11 @@ Connection Types :param platform: Specify the platform to be used. The generic :class:`~devlib.platform.Platform` class is used by default. :param sudo_cmd: Specify the format of the command used to grant sudo access. - :param strict_host_check: Specify the ssh connection parameter ``StrictHostKeyChecking``, + :param strict_host_check: Specify the ssh connection parameter + ``StrictHostKeyChecking``. If a path is passed + rather than a boolean, it will be taken for a + ``known_hosts`` file. Otherwise, the default + ``$HOME/.ssh/known_hosts`` will be used. :param use_scp: Use SCP for file transfers, defaults to SFTP. :param poll_transfers: Specify whether file transfers should be polled. Polling monitors the progress of file transfers and periodically