Python paramiko.SSHConfig() Examples
The following are 16
code examples of paramiko.SSHConfig().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
paramiko
, or try the search function
.
Example #1
Source File: fortios.py From pyfg with Apache License 2.0 | 9 votes |
def open(self): """ Opens the ssh session with the device. """ logger.debug('Connecting to device %s, vdom %s' % (self.hostname, self.vdom)) self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) cfg = { 'hostname': self.hostname, 'timeout': self.timeout, 'username': self.username, 'password': self.password, 'key_filename': self.keyfile } if os.path.exists(os.path.expanduser("~/.ssh/config")): ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") with io.open(user_config_file, 'rt', encoding='utf-8') as f: ssh_config.parse(f) host_conf = ssh_config.lookup(self.hostname) if host_conf: if 'proxycommand' in host_conf: cfg['sock'] = paramiko.ProxyCommand(host_conf['proxycommand']) if 'user' in host_conf: cfg['username'] = host_conf['user'] if 'identityfile' in host_conf: cfg['key_filename'] = host_conf['identityfile'] if 'hostname' in host_conf: cfg['hostname'] = host_conf['hostname'] self.ssh.connect(**cfg)
Example #2
Source File: ssh.py From mqttwarn with Eclipse Public License 2.0 | 6 votes |
def credentials(host, user=None, pwd=None, port=22): c = {} if user is None and pwd is None: config = paramiko.SSHConfig() p = os.path.expanduser('~') + '/.ssh/config' config.parse(open(p)) o = config.lookup(host) ident = o['identityfile'] if type(ident) is list: ident = ident[0] if 'port' not in o: o['port'] = port c = {'hostname': o['hostname'], 'port': int(o['port']), 'username': o['user'], 'key_filename': ident} else: c = {'hostname': host, 'port': port, 'username': user, 'password': pwd} return c
Example #3
Source File: __init__.py From aetros-cli with MIT License | 6 votes |
def get_ssh_key_for_host(host): ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) user_config = ssh_config.lookup(host) if 'identityfile' in user_config: path = os.path.expanduser(user_config['identityfile'][0]) if not os.path.exists(path): raise Exception("Specified IdentityFile "+path + " for " + host + " in ~/.ssh/config not existing anymore.") return path
Example #4
Source File: vagrant.py From learning-tools with MIT License | 6 votes |
def get_a_ssh_config(box_name): """Gives back a map of all the machine's ssh configurations""" output = to_text(subprocess.check_output(["vagrant", "ssh-config", box_name]), errors='surrogate_or_strict') config = SSHConfig() config.parse(StringIO(output)) host_config = config.lookup(box_name) # man 5 ssh_config: # > It is possible to have multiple identity files ... # > all these identities will be tried in sequence. for id in host_config['identityfile']: if os.path.isfile(id): host_config['identityfile'] = id return dict((v, host_config[k]) for k, v in _ssh_to_ansible) # List out servers that vagrant has running # ------------------------------
Example #5
Source File: sr_sftp.py From sarracenia with GNU General Public License v2.0 | 6 votes |
def __init__(self, parent) : parent.logger.debug("sr_sftp __init__") sr_proto.__init__(self,parent) self.user_cache_dir = parent.user_cache_dir # sftp command times out after 20 secs # this setting is different from the computed iotime (sr_proto) self.init() self.ssh_config = None try : self.ssh_config = paramiko.SSHConfig() ssh_config = os.path.expanduser('~/.ssh/config') if os.path.isfile(ssh_config) : fp = open(ssh_config,'r') self.ssh_config.parse(fp) fp.close() except: self.logger.error("sr_sftp/__init__: unable to load ssh config %s" % ssh_config) self.logger.debug('Exception details: ', exc_info=True) # cd
Example #6
Source File: ssh_helper.py From quads with GNU General Public License v3.0 | 6 votes |
def connect(self): ssh = SSHClient() config = SSHConfig() with open(os.path.expanduser("~/.ssh/config")) as _file: config.parse(_file) host_config = config.lookup(self.host) ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.load_system_host_keys() ssh.connect( self.host, username=self.user, password=self.password, key_filename=host_config["identityfile"][0], allow_agent=False, timeout=30, ) transport = ssh.get_transport() channel = transport.open_session() channel.setblocking(1) return ssh
Example #7
Source File: schecks.py From check-linux-by-ssh with MIT License | 6 votes |
def connect(hostname, port, ssh_key_file, passphrase, user): # If we are in a localhost case, don't play with ssh if is_local(hostname): return LocalExec() # Maybe paramiko is missing, but now we relly need ssh... if paramiko is None: print "ERROR : this plugin needs the python-paramiko module. Please install it" sys.exit(2) if not os.path.exists(os.path.expanduser(ssh_key_file)): err = "Error : missing ssh key file. please specify it with -i parameter" raise Exception(err) ssh_key_file = os.path.expanduser(ssh_key_file) client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) cfg = {'hostname': hostname, 'port': port, 'username': user, 'key_filename': ssh_key_file, 'password': passphrase} user_config = ssh_config.lookup(cfg['hostname']) for k in ('hostname', port, 'username', 'key_filename', 'password'): if k in user_config: cfg[k] = user_config[k] if 'proxycommand' in user_config: cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand']) try: client.connect(**cfg) except Exception, exp: err = "Error : connexion failed '%s'" % exp print err sys.exit(2)
Example #8
Source File: flow.py From pwnypack with MIT License | 5 votes |
def connect(self, hostname, *args, **kwargs): connect = super(SSHClient, self).connect options = inspect.getcallargs(connect, hostname, *args, **kwargs) del options['self'] ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) user_config = ssh_config.lookup(options['hostname']) if 'hostname' in user_config: options['hostname'] = user_config['hostname'] if 'port' not in kwargs and 'port' in user_config: options['port'] = int(user_config['port']) if 'username' not in kwargs and 'user' in user_config: options['username'] = user_config['user'] if 'key_filename' not in kwargs and 'identityfile' in user_config: options['key_filename'] = user_config['identityfile'] if 'timeout' not in kwargs and 'connecttimeout' in user_config: options['timeout'] = int(user_config['connecttimeout']) if 'look_for_keys' not in kwargs and 'allow_agent' not in kwargs and 'identiesonly' in user_config: options['look_for_keys'] = options['allow_agent'] = user_config['identiesonly'] == 'no' if 'gss_auth' not in kwargs and 'gssapiauthentication' in user_config: options['gss_auth'] = user_config['gssapiauthentication'] == 'yes' if 'gss_kex' not in kwargs and 'gssapikeyexchange' in user_config: options['gss_key'] = user_config['gssapikeyexchange'] == 'yes' if 'gss_deleg_creds' not in kwargs and 'gssapidelegatecredentials' in user_config: options['gss_deleg_creds'] = user_config['gssapidelegatecredentials'] == 'yes' if 'compress' not in kwargs and 'compression' in user_config: options['compress'] = user_config['compress'] == 'yes' if 'sock' not in kwargs and 'proxycommand' in user_config: options['sock'] = paramiko.ProxyCommand(user_config['proxycommand']) return connect(**options)
Example #9
Source File: paramiko.py From testinfra with Apache License 2.0 | 5 votes |
def client(self): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.WarningPolicy()) cfg = { "hostname": self.host.name, "port": int(self.host.port) if self.host.port else 22, "username": self.host.user, "timeout": self.timeout, } if 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) else: # fallback reading ~/.ssh/config default_ssh_config = os.path.join( os.path.expanduser('~'), '.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) if self.ssh_identity_file: cfg["key_filename"] = self.ssh_identity_file client.connect(**cfg) return client
Example #10
Source File: sshclient.py From ldpush with Apache License 2.0 | 5 votes |
def __init__(self): """Read the configuration if present and store it for later. Check if the flag --paramiko_ssh_config was set and parse the configuration file. """ # This flag may be set by another thread concurrently. We will # check the value again under a lock. if SshOptions._need_init: try: with SshOptions._lock: if SshOptions._need_init and FLAGS.paramiko_ssh_config: logging.debug( 'Reading configuration from %s', FLAGS.paramiko_ssh_config) try: configfile = open(FLAGS.paramiko_ssh_config) ssh_config = paramiko.SSHConfig() ssh_config.parse(configfile) SshOptions._ssh_options = ssh_config except Exception as e: # pylint: disable=broad-except # Unfortunately paramiko raises "Exception" if there is an # error in the config file. logging.fatal('Unable to read or parse "%s": %s', FLAGS.paramiko_ssh_config, e) finally: SshOptions._need_init = False
Example #11
Source File: paramiko_ssh.py From st2 with Apache License 2.0 | 5 votes |
def _get_ssh_config_for_host(self, host): ssh_config_info = {} ssh_config_parser = paramiko.SSHConfig() try: with open(self.ssh_config_file) as f: ssh_config_parser.parse(f) except IOError as e: raise Exception('Error accessing ssh config file %s. Code: %s Reason %s' % (self.ssh_config_file, e.errno, e.strerror)) ssh_config = ssh_config_parser.lookup(host) self.logger.info('Parsed SSH config file contents: %s', ssh_config) if ssh_config: for k in ('hostname', 'user', 'port'): if k in ssh_config: ssh_config_info[k] = ssh_config[k] if 'identityfile' in ssh_config: key_file = ssh_config['identityfile'] if type(key_file) is list: key_file = key_file[0] ssh_config_info['identityfile'] = key_file if 'proxycommand' in ssh_config: ssh_config_info['sock'] = paramiko.ProxyCommand(ssh_config['proxycommand']) return ssh_config_info
Example #12
Source File: scp_upload.py From panotti with MIT License | 5 votes |
def scp_upload(src_blob='Preproc.tar.gz', dst_blob="~", options={'hostname': 'lecun', 'username': 'shawley'}, progress=simple_callback): # from https://gist.github.com/acdha/6064215 #--- Make the Paramiko SSH thing use my .ssh/config file (b/c I like ProxyCommand!) client = SSHClient() client.load_system_host_keys() client._policy = WarningPolicy() client.set_missing_host_key_policy(WarningPolicy()) # hmm. WarningPolicy? Most people use AutoAddPolicy. ssh_config = SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) cfg = {'hostname': options['hostname'], 'username': options["username"]} user_config = ssh_config.lookup(cfg['hostname']) for k in ('hostname', 'username', 'port'): if k in user_config: cfg[k] = user_config[k] if 'proxycommand' in user_config: cfg['sock'] = ProxyCommand(user_config['proxycommand']) client.connect(**cfg) socket_timeout = None # number of seconds for timeout. None = never timeout. TODO: None means program may hang. But timeouts are annoying! # SCPCLient takes a paramiko transport and progress callback as its arguments. scp = SCPClient(client.get_transport(), progress=progress, socket_timeout=socket_timeout) # NOW we can finally upload! (in a separate process) #scp.put(src_blob, dst_blob) # now in scp_thread # we want this to be non-blocking so we stick it in a thread thread = threading.Thread(target=scp_thread, args=(scp,src_blob, dst_blob) ) thread.start() #scp.close() # now in scp_thread
Example #13
Source File: vmtools.py From fdroidserver with GNU Affero General Public License v3.0 | 5 votes |
def sshinfo(self): """Get ssh connection info for a vagrant VM :returns: A dictionary containing 'hostname', 'port', 'user' and 'idfile' """ import paramiko try: sshconfig_path = os.path.join(self.srvdir, 'sshconfig') with open(sshconfig_path, 'wb') as fp: fp.write(_check_output(['vagrant', 'ssh-config'], cwd=self.srvdir)) vagranthost = 'default' # Host in ssh config file sshconfig = paramiko.SSHConfig() with open(sshconfig_path, 'r') as f: sshconfig.parse(f) sshconfig = sshconfig.lookup(vagranthost) idfile = sshconfig['identityfile'] if isinstance(idfile, list): idfile = idfile[0] elif idfile.startswith('"') and idfile.endswith('"'): idfile = idfile[1:-1] return {'hostname': sshconfig['hostname'], 'port': int(sshconfig['port']), 'user': sshconfig['user'], 'idfile': idfile} except subprocess.CalledProcessError as e: raise FDroidBuildVmException("Error getting ssh config") from e
Example #14
Source File: resources.py From dagster with Apache License 2.0 | 4 votes |
def __init__( self, remote_host, remote_port, username=None, password=None, key_file=None, key_string=None, timeout=10, keepalive_interval=30, compress=True, no_host_key_check=True, allow_host_key_change=False, logger=None, ): self.remote_host = check.str_param(remote_host, 'remote_host') self.remote_port = check.opt_int_param(remote_port, 'remote_port') self.username = check.opt_str_param(username, 'username') self.password = check.opt_str_param(password, 'password') self.key_file = check.opt_str_param(key_file, 'key_file') self.timeout = check.opt_int_param(timeout, 'timeout') self.keepalive_interval = check.opt_int_param(keepalive_interval, 'keepalive_interval') self.compress = check.opt_bool_param(compress, 'compress') self.no_host_key_check = check.opt_bool_param(no_host_key_check, 'no_host_key_check') self.allow_host_key_change = check.opt_bool_param( allow_host_key_change, 'allow_host_key_change' ) self.log = logger self.host_proxy = None # Create RSAKey object from private key string self.key_obj = key_from_str(key_string) if key_string is not None else None # Auto detecting username values from system if not self.username: logger.debug( 'username to ssh to host: %s is not specified. Using system\'s default provided by' ' getpass.getuser()' % self.remote_host ) self.username = getpass.getuser() user_ssh_config_filename = os.path.expanduser('~/.ssh/config') if os.path.isfile(user_ssh_config_filename): ssh_conf = paramiko.SSHConfig() ssh_conf.parse(open(user_ssh_config_filename)) host_info = ssh_conf.lookup(self.remote_host) if host_info and host_info.get('proxycommand'): self.host_proxy = paramiko.ProxyCommand(host_info.get('proxycommand')) if not (self.password or self.key_file): if host_info and host_info.get('identityfile'): self.key_file = host_info.get('identityfile')[0]
Example #15
Source File: sftp_artifact_repo.py From mlflow with Apache License 2.0 | 4 votes |
def __init__(self, artifact_uri, client=None): self.uri = artifact_uri parsed = urllib.parse.urlparse(artifact_uri) self.config = { 'host': parsed.hostname, 'port': parsed.port, 'username': parsed.username, 'password': parsed.password } self.path = parsed.path if client: self.sftp = client else: import pysftp import paramiko if self.config['host'] is None: self.config['host'] = 'localhost' ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) user_config = ssh_config.lookup(self.config['host']) if 'hostname' in user_config: self.config['host'] = user_config['hostname'] if self.config.get('username', None) is None and 'user' in user_config: self.config['username'] = user_config['user'] if self.config.get('port', None) is None: if 'port' in user_config: self.config['port'] = int(user_config['port']) else: self.config['port'] = 22 if 'identityfile' in user_config: self.config['private_key'] = user_config['identityfile'][0] self.sftp = pysftp.Connection(**self.config) super(SFTPArtifactRepository, self).__init__(artifact_uri)
Example #16
Source File: sshtunnel.py From sshtunnel with MIT License | 4 votes |
def _read_ssh_config(ssh_host, ssh_config_file, ssh_username=None, ssh_pkey=None, ssh_port=None, ssh_proxy=None, compression=None, logger=None): """ Read ssh_config_file and tries to look for user (ssh_username), identityfile (ssh_pkey), port (ssh_port) and proxycommand (ssh_proxy) entries for ssh_host """ ssh_config = paramiko.SSHConfig() if not ssh_config_file: # handle case where it's an empty string ssh_config_file = None # Try to read SSH_CONFIG_FILE try: # open the ssh config file with open(os.path.expanduser(ssh_config_file), 'r') as f: ssh_config.parse(f) # looks for information for the destination system hostname_info = ssh_config.lookup(ssh_host) # gather settings for user, port and identity file # last resort: use the 'login name' of the user ssh_username = ( ssh_username or hostname_info.get('user') ) ssh_pkey = ( ssh_pkey or hostname_info.get('identityfile', [None])[0] ) ssh_host = hostname_info.get('hostname') ssh_port = ssh_port or hostname_info.get('port') proxycommand = hostname_info.get('proxycommand') ssh_proxy = ssh_proxy or (paramiko.ProxyCommand(proxycommand) if proxycommand else None) if compression is None: compression = hostname_info.get('compression', '') compression = True if compression.upper() == 'YES' else False except IOError: if logger: logger.warning( 'Could not read SSH configuration file: {0}' .format(ssh_config_file) ) except (AttributeError, TypeError): # ssh_config_file is None if logger: logger.info('Skipping loading of ssh configuration file') finally: return (ssh_host, ssh_username or getpass.getuser(), ssh_pkey, int(ssh_port) if ssh_port else 22, # fallback value ssh_proxy, compression)