From 6b8284640e6b6b99cd68e2ed6bf0e572ed88e58a Mon Sep 17 00:00:00 2001 From: Olle Lundberg Date: Fri, 30 Mar 2012 15:59:58 +0200 Subject: [PATCH] Add support for variable expansion in SSHConfig (cherry picked from commit 31482a46d6c360e00284a7ccfd68362891ab316b) --- paramiko/config.py | 49 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/paramiko/config.py b/paramiko/config.py index d30080a..75c54b4 100644 --- a/paramiko/config.py +++ b/paramiko/config.py @@ -21,7 +21,10 @@ L{SSHConfig}. """ import fnmatch +import os +import socket +SSH_PORT=22 class SSHConfig (object): """ @@ -115,18 +118,56 @@ class SSHConfig (object): Return a dict of config options with expanded substitutions for a given hostname. - For the moment only expansion of the %h substitution in the - hostname config is supported. + Please refer to man ssh_config(5) for the parameters that + are replaced. @param config: the config for the hostname @type hostname: dict @param hostname: the hostname that the config belongs to @type hostname: str """ - #TODO: Add support for expansion of all substitution parameters - #TODO: see man ssh_config(5) + if 'hostname' in config: config['hostname'] = config['hostname'].replace('%h',hostname) else: config['hostname'] = hostname + + if 'port' in config: + port = config['port'] + else: + port = SSH_PORT + + user = os.getenv('USER') + if 'user' in config: + remoteuser = config['user'] + else: + remoteuser = user + + host = socket.gethostname().split('.')[0] + fqdn = socket.getfqdn() + homedir = os.path.expanduser('~') + replacements = {'controlpath' : + [ + ('%h', config['hostname']), + ('%l', fqdn), + ('%L', host), + ('%n', hostname), + ('%p', port), + ('%r', remoteuser), + ('%u', user) + ], + 'identityfile' : + [ + ('~', homedir), + ('%d', homedir), + ('%h', config['hostname']), + ('%l', fqdn), + ('%u', user), + ('%r', remoteuser) + ] + } + for k in config: + if k in replacements: + for find, replace in replacements[k]: + config[k] = config[k].replace(find, str(replace)) return config