Update SSH connection parameters based on contents of SSH 'config' file.

        :param dict_arg: Dictionary of SSH connection parameters
        :type dict_arg: dict
13312
def _use_ssh_config(self, dict_arg):
        
        connect_dict = dict_arg.copy()

        # Use SSHConfig to generate source content.
        full_path = path.abspath(path.expanduser(self.ssh_config_file))
        if path.exists(full_path):
            ssh_config_instance = paramiko.SSHConfig()
            with io.open(full_path, "rt", encoding="utf-8") as f:
                ssh_config_instance.parse(f)
                source = ssh_config_instance.lookup(self.host)
        else:
            source = {}

        if "proxycommand" in source:
            proxy = paramiko.ProxyCommand(source["proxycommand"])
        elif "ProxyCommand" in source:
            proxy = paramiko.ProxyCommand(source["ProxyCommand"])
        else:
            proxy = None

        # Only update 'hostname', 'sock', 'port', and 'username'
        # For 'port' and 'username' only update if using object defaults
        if connect_dict["port"] == 22:
            connect_dict["port"] = int(source.get("port", self.port))
        if connect_dict["username"] == "":
            connect_dict["username"] = source.get("user", self.username)
        if proxy:
            connect_dict["sock"] = proxy
        connect_dict["hostname"] = source.get("hostname", self.host)

        return connect_dict
591210
def configure_args(self, arguments):
        

        module, key, config_path = self.check_file_paths(arguments.module,
                                                         arguments.key,
                                                         arguments.config)
        log_dir = self.check_directory_paths(arguments.log_dir)

        if arguments.repository_url is None:
            url = default_config['repository']['url']
        else:
            url = arguments.repository_url

        args_config = dict(aws=dict(bucket=arguments.bucket),
                           logging=dict(dir=arguments.log_dir,
                                        prefix=arguments.log_prefix),
                           workers=arguments.workers,
                           repository=dict(enabled=arguments.repository,
                                           url=url,
                                           manifest=arguments.repository_manifest,
                                           gpg_verify=arguments.gpg_verify))

        if arguments.server is not None:

            jump_host = None
            if arguments.jump_server is not None:
                if arguments.jump_port is not None:
                    jump_port = int(arguments.jump_port)
                else:
                    jump_port = None
                jump_host = dict(zip(jump_host_allowed_keys,
                                     [arguments.jump_server,
                                      jump_port,
                                      arguments.jump_username,
                                      arguments.jump_password,
                                      arguments.jump_key]))

            if arguments.port is not None:
                port = int(arguments.port)
            else:
                port = None
            host = dict(zip(host_allowed_keys,
                            [arguments.server, port, arguments.username,
                             arguments.password, module, key,
                             arguments.filename, jump_host]))
            args_config['hosts'] = []
            args_config['hosts'].append(host)

        if config_path is not None:
            try:
                config = self.load_config(config_path)
                self.validate_config(config)
                args_config.update(config)
            except YAMLError as ex:
                logger.warn('Invalid yaml Format: {0}'.format(ex))
                raise
            except InvalidConfigurationError as ex:
                logger.warn(ex)
                raise

        return args_config
523539
def _connect_ssh(spec):
    
    if C.HOST_KEY_CHECKING:
        check_host_keys = 'enforce'
    else:
        check_host_keys = 'ignore'

    # #334: tilde-expand private_key_file to avoid implementation difference
    # between Python and OpenSSH.
    private_key_file = spec.private_key_file()
    if private_key_file is not None:
        private_key_file = os.path.expanduser(private_key_file)

    return {
        'method': 'ssh',
        'kwargs': {
            'check_host_keys': check_host_keys,
            'hostname': spec.remote_addr(),
            'username': spec.remote_user(),
            'compression': convert_bool(
                default(spec.mitogen_ssh_compression(), True)
            ),
            'password': spec.password(),
            'port': spec.port(),
            'python_path': spec.python_path(),
            'identity_file': private_key_file,
            'identities_only': False,
            'ssh_path': spec.ssh_executable(),
            'connect_timeout': spec.ansible_ssh_timeout(),
            'ssh_args': spec.ssh_args(),
            'ssh_debug_level': spec.mitogen_ssh_debug_level(),
            'remote_name': get_remote_name(spec),
        }
    }
1112618
def update_args(self, args):
        
        for cfg in args:
            keys, v = cfg.split('=', maxsplit=1)
            keylist = keys.split('.')

            dic = self
            for i, k in enumerate(keylist[:-1]):
                assert k in dir(dic), "Unknown config key: {}".format(keys)
                dic = getattr(dic, k)
            key = keylist[-1]

            oldv = getattr(dic, key)
            if not isinstance(oldv, str):
                v = eval(v)
            setattr(dic, key, v)
1015823
def ssh_args(conn):
    """"""
    I, = conn.identities
    identity = I.identity_dict
    pubkey_tempfile, = conn.public_keys_as_files()

    args = []
    if 'port' in identity:
        args += ['-p', identity['port']]
    if 'user' in identity:
        args += ['-l', identity['user']]

    args += ['-o', 'IdentityFile={}'.format(pubkey_tempfile.name)]
    args += ['-o', 'IdentitiesOnly=true']
    return args + [identity['host']]
801483
def set(self, host, **kwargs):
        
        self.__check_host_args(host, kwargs)

        def update_line(key, value):
            """Produce new config line"""
            return "  %s %s" % (key, value)

        for key, values in kwargs.items():
            if type(values) not in [list, tuple]:  # pylint: disable=unidiomatic-typecheck
                values = [values]

            lower_key = key.lower()
            update_idx = [idx for idx, x in enumerate(self.lines_)
                          if x.host == host and x.key.lower() == lower_key]
            extra_remove = []
            for idx in update_idx:
                if values:  # values available, update the line
                    value = values.pop()
                    self.lines_[idx].line = update_line(self.lines_[idx].key, value)
                    self.lines_[idx].value = value
                else:                # no more values available, remove the line
                    extra_remove.append(idx)

            for idx in reversed(sorted(extra_remove)):
                del self.lines_[idx]

            if values:
                mapped_key = _remap_key(key)
                max_idx = max([idx for idx, line in enumerate(self.lines_) if line.host == host])
                for value in values:
                    self.lines_.insert(max_idx + 1, ConfigLine(line=update_line(mapped_key, value),
                                                               host=host, key=mapped_key,
                                                               value=value))
1334675
def set_key(key: str, value: str) -> dict:
    
    if not _conf.path:
        return {}

    if "toml" in _conf.path:
        with open(_conf.path, "r") as f:
            parser = parse(f.read())
        parser["tool"]["commitizen"][key] = value
        with open(_conf.path, "w") as f:
            f.write(parser.as_string())
    else:
        parser = configparser.ConfigParser()
        parser.read(_conf.path)
        parser["commitizen"][key] = value
        with open(_conf.path, "w") as f:
            parser.write(f)

    return _conf.config
1068327
def from_args(cls: Type[ConfigT], args: Namespace) -> ConfigT:
        
        parsed_args = cls.parse_args(args)
        return cls(args, host=args.host, port=args.port, debug=args.debug,
                   reject_insecure_auth=not args.insecure_login,
                   cert_file=args.cert, key_file=args.key,
                   **parsed_args)
614503
def update_config(self, config):
    
    path = self._path() + '/config'
    resp = self._get_resource_root().put(path, data = config_to_json(config))
    return json_to_config(resp)
746935
def _prepare_connection(**kwargs):
    '''
    
    '''
    paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs)
    ssh = paramiko.SSHClient()
    if paramiko_kwargs.pop('auto_add_policy', False):
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(**paramiko_kwargs)
    scp_client = scp.SCPClient(ssh.get_transport(),
                               **scp_kwargs)
    return scp_client
925968
def update_config(cls, config_file, config):
        
        need_save = False
        # delete old env key
        if 'api' in config and 'env' in config['api']:
            del config['api']['env']
            need_save = True
        # convert old ssh_key configuration entry
        ssh_key = config.get('ssh_key')
        sshkeys = config.get('sshkey')
        if ssh_key and not sshkeys:
            config.update({'sshkey': [ssh_key]})
            need_save = True
        elif ssh_key and sshkeys:
            config.update({'sshkey': sshkeys.append(ssh_key)})
            need_save = True
        # remove old value
        if ssh_key:
            del config['ssh_key']
            need_save = True

        # save to disk
        if need_save:
            cls.save(config_file, config)
592198
def _GetConnectionArgs(host=None,
                       port=None,
                       user=None,
                       password=None,
                       database=None,
                       client_key_path=None,
                       client_cert_path=None,
                       ca_cert_path=None):
  """"""
  connection_args = dict(
      autocommit=False, use_unicode=True, charset=CHARACTER_SET)

  if host is not None:
    connection_args["host"] = host

  if port is not None:
    connection_args["port"] = port

  if user is not None:
    connection_args["user"] = user

  if password is not None:
    connection_args["passwd"] = password

  if database is not None:
    connection_args["db"] = database

  if client_key_path is not None:
    connection_args["ssl"] = {
        "key": client_key_path,
        "cert": client_cert_path,
        "ca": ca_cert_path,
    }

  return connection_args
436178
def config(_config=None, **kwargs):
    
    if _config is None:
        _config = {}
    _config.update(kwargs)

    def wrapper(func):
        func._config = _config
        return func
    return wrapper
265891
def update_config(self, cluster_config):
        
        for key, attr in [
                ('ssh_to', 'ssh_to'),
        ]:
            oldvalue = getattr(self, attr)
            try:
                newvalue = cluster_config[key]
            except KeyError:
                continue
            if key in cluster_config and newvalue != oldvalue:
                setattr(self, attr, newvalue)
                log.debug(
                    "Configuration attribute `%s` updated: %s -> %s",
                    key, oldvalue, newvalue)
614514
def get_sshconfig():
    
    '''

    with open(os.path.expanduser('~/.ssh/config')) as f:
        cfg = paramiko.SSHConfig()
        cfg.parse(f)
        ret_dict = {}
        for d in cfg._config:
            _copy = dict(d)
            # Avoid buggy behavior with strange host definitions, we need
            # Hostname and not Host.
            del _copy['host']
            for host in d['host']:
                ret_dict[host] = _copy['config']

        return ret_dict
309147
def add_arguments(cls, parser, sys_arg_list=None):
        
        parser.add_argument('-f', '--file', dest='file', required=True,
                            help="config file for routing groups "
                                 "(only in configfile mode)")
        return ["file"]
418994
def load_cli_config(args):
    
    default_cli_config = _load_default_cli_config()
    toml_config = _load_toml_cli_config()

    for config in (toml_config, default_cli_config):
        for key, val in config.items():
            if key in args and getattr(args, key) is not None:
                pass
            else:
                setattr(args, key, val)