Skip to content

Commit

Permalink
wrap SSH client setup in a function
Browse files Browse the repository at this point in the history
This makes it easier to monkeypatch to earlier versions. With this
patch, I can copy-paste the setup_ssh_client() function into my code
and monkeypatch older fabric versions with:

    # hack to fix Fabric key policy:
    # #2071
    def safe_open(self):
        SaferConnection.setup_ssh_client(self)
        Connection.open_orig(self)

    class SaferConnection(Connection):
        # this function is a copy-paste from #2072
        def setup_ssh_client(self):
            # [...]

    Connection.open_orig = Connection.open
    Connection.open = safe_open

This is otherwise a noop.
  • Loading branch information
anarcat committed Sep 6, 2023
1 parent b8319de commit 19db567
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions fabric/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,18 +456,8 @@ def __init__(
self.connect_kwargs = self.resolve_connect_kwargs(connect_kwargs)

#: The `paramiko.client.SSHClient` instance this connection wraps.
client = SSHClient()
if self.default_host_key_policy is not None:
logging.debug('host key policy: %s', self.default_host_key_policy)
client.set_missing_host_key_policy(self.default_host_key_policy())
known_hosts = self.ssh_config.get('UserKnownHostsFile'.lower(),
'~/.ssh/known_hosts')
logging.debug('loading host keys from %s', known_hosts)
# multiple keys, seperated by whitespace, can be provided
for filename in [os.path.expanduser(f) for f in known_hosts.split()]:
if os.path.exists(filename):
client.load_host_keys(filename)
self.client = client
self.client = SSHClient()
self.setup_ssh_client()

#: A convenience handle onto the return value of
#: ``self.client.get_transport()`` (after connection time).
Expand All @@ -479,6 +469,21 @@ def __init__(
#: inline.
self.inline_ssh_env = inline_ssh_env

def setup_ssh_client(self):
if self.default_host_key_policy is not None:
logging.debug("host key policy: %s", self.default_host_key_policy)
self.client.set_missing_host_key_policy(
self.default_host_key_policy()
)
known_hosts = self.ssh_config.get(
"UserKnownHostsFile".lower(), "~/.ssh/known_hosts"
)
logging.debug("loading host keys from %s", known_hosts)
# multiple keys, seperated by whitespace, can be provided
for filename in [os.path.expanduser(f) for f in known_hosts.split()]:
if os.path.exists(filename):
self.client.load_host_keys(filename)

def resolve_connect_kwargs(self, connect_kwargs):
# TODO: is it better to pre-empt conflicts w/ manually-handled
# connect() kwargs (hostname, username, etc) here or in open()? We're
Expand Down

0 comments on commit 19db567

Please sign in to comment.