Only parse user SSH config once.
@@ -11,9 +11,21 @@ from paramiko import (
SSHClient as ParamikoClient,
)
+from pyinfra.api.util import memoize
+
from .config import SSHConfig
+@memoize
+def get_ssh_config():
+ user_config_file = os.path.expanduser('~/.ssh/config')
+ if os.path.exists(user_config_file):
+ with open(user_config_file) as f:
+ ssh_config = SSHConfig()
+ ssh_config.parse(f)
+ return ssh_config
+
+
class SSHClient(ParamikoClient):
'''
An SSHClient which honors ssh_config and supports proxyjumping
@@ -35,12 +47,9 @@ class SSHClient(ParamikoClient):
def parse_config(self, hostname):
cfg = {'port': 22}
- user_config_file = os.path.expanduser('~/.ssh/config')
- if os.path.exists(user_config_file):
- with open(user_config_file) as f:
- ssh_config = SSHConfig()
- ssh_config.parse(f)
+ ssh_config = get_ssh_config()
host_config = ssh_config.lookup(hostname)
+
if 'hostname' in host_config:
hostname = host_config['hostname']
if 'user' in host_config:
@@ -67,6 +76,7 @@ class SSHClient(ParamikoClient):
hops[i + 1])
sock = c.gateway(target, target_config['port'])
cfg['sock'] = sock
+
return hostname, cfg
def derive_shorthand(self, host_string):
