当前位置: 首页>>代码示例>>Python>>正文


Python SSHConfig.parse方法代码示例

本文整理汇总了Python中paramiko.config.SSHConfig.parse方法的典型用法代码示例。如果您正苦于以下问题:Python SSHConfig.parse方法的具体用法?Python SSHConfig.parse怎么用?Python SSHConfig.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在paramiko.config.SSHConfig的用法示例。


在下文中一共展示了SSHConfig.parse方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _annotate_hosts_with_ssh_config_info

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def _annotate_hosts_with_ssh_config_info():
    from os.path import expanduser
    from paramiko.config import SSHConfig

    def hostinfo(host, config):
        hive = config.lookup(host)
        if 'hostname' in hive:
            host = hive['hostname']
        if 'user' in hive:
            host = '%[email protected]%s' % (hive['user'], host)
        if 'port' in hive:
            host = '%s:%s' % (host, hive['port'])
        return host

    try:
        config_file = file(expanduser('~/.ssh/config'))
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)
        keys = [config.lookup(host).get('identityfile', None)
            for host in env.hosts]
        env.key_filename = [expanduser(key) for key in keys if key is not None]
        env.hosts = [hostinfo(host, config) for host in env.hosts]

        for role, rolehosts in env.roledefs.items():
            env.roledefs[role] = [hostinfo(host, config) for host in rolehosts]
开发者ID:yekeqiang,项目名称:fabric_project,代码行数:30,代码来源:fabfile_ssh_config.py

示例2: parse_ssh_config

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def parse_ssh_config(file_obj):
    """
    Provided only as a backward-compatible wrapper around L{SSHConfig}.
    """
    config = SSHConfig()
    config.parse(file_obj)
    return config
开发者ID:ufosky-server,项目名称:MultiversePlatform,代码行数:9,代码来源:util.py

示例3: getSSHInfoForHost

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def getSSHInfoForHost(host):
    """ Inspired by:
        http://markpasc.typepad.com/blog/2010/04/loading-ssh-config-settings-for-fabric.html """

    from os.path import expanduser
    from paramiko.config import SSHConfig

    key = None
    key_filename = None
    host = host

    def hostinfo(host, config):
        hive = config.lookup(host)
        if 'hostname' in hive:
            host = hive['hostname']
        if 'user' in hive:
            host = '%[email protected]%s' % (hive['user'], host)
        if 'port' in hive:
            host = '%s:%s' % (host, hive['port'])
        return host

    try:
        config_file = file(expanduser('~/.ssh/config'))
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)
        key = config.lookup(host).get('identityfile', None)
        if key != None: key_filename = expanduser(key)
        host = hostinfo(host, config)
    return key_filename, host
开发者ID:Eonblast,项目名称:voltdb,代码行数:34,代码来源:fabric_ssh_config.py

示例4: main

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def main(working_dir=None):
    if working_dir is None:
        return      

    logentriesprovisioning.constants.set_working_dir(working_dir)
    logentriesprovisioning.constants.set_account_key(None)
    logentriesprovisioning.constants.set_logentries_logging()

    if working_dir is None:
        ssh_config_name = 'ssh_config'
    else:
        ssh_config_name = '%s/ssh_config'%working_dir

    env.use_ssh_config = True
    try:
        config_file = file(ssh_config_name)
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)
        env._ssh_config = config
        for i in range(0,len(config._config)):
            print str(i), ' - ' , config._config[i]

    list_hosts = []
    for host_config in env._ssh_config._config:
        print host_config
        if host_config['host'][0]!='*':
            list_hosts.extend(host_config['host'])

    execute(sync,hosts=list_hosts)
开发者ID:m0wfo,项目名称:le_aws,代码行数:34,代码来源:sync_log.py

示例5: annotate_hosts_with_ssh_config_info

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def annotate_hosts_with_ssh_config_info():
    """
    Load settings from ~/.ssh/config
    NOTE: Need to define env.hosts first.
    Code from http://markpasc.typepad.com/blog/2010/04/loading-ssh-config-settings-for-fabric.html
    """
    def hostinfo(host, config):
        hive = config.lookup(host)
        if 'user' in hive:
            host = '%[email protected]%s' % (hive['user'], host)
        if 'port' in hive:
            host = '%s:%s' % (host, hive['port'])
        return host

    try:
        config_file = file(expanduser('~/.ssh/config'))
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)
        keys = [config.lookup(host).get('identityfile', None)
            for host in env.hosts]
        env.key_filename = [key for key in keys if key is not None]
        env.hosts = [hostinfo(host, config) for host in env.hosts]
开发者ID:pombredanne,项目名称:fabricrecipes,代码行数:27,代码来源:common.py

示例6: ssh_config

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def ssh_config(host):
    from os.path import expanduser
    from paramiko.config import SSHConfig

    def hostinfo(host, config):
        hive = config.lookup(host)
        if 'hostname' in hive:
            host = hive['hostname']
        if 'user' in hive:
            host = '%[email protected]%s' % (hive['user'], host)
        if 'port' in hive:
            host = '%s:%s' % (host, hive['port'])
        return host

    try:
        config_file = file(expanduser('~/.ssh/config'))
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)
        key = config.lookup(host).get('identityfile', None)
        key_filename = expanduser(key)
        
        env.key_filename = [key_filename] if key_filename else []
        return hostinfo(host, config)
开发者ID:sunlightlabs,项目名称:regulations-scraper,代码行数:28,代码来源:ssh_util.py

示例7: __init__

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
    def __init__(self, hostname, user = None, filename = None):
        #set defaults
        if filename == None:
            filename = os.path.expanduser('~/.ssh/config')

        #read config file
        ssh_config = SSHConfig()
        with open(filename) as config_file:
            ssh_config.parse(config_file)

        self.update(ssh_config.lookup(hostname))

        self.defaults={'port': 22, 'user': getpass.getuser(), 'hostname': hostname, 'hostkeyalias': hostname}

        if user != None:
            self['user'] = user
开发者ID:h8liu,项目名称:cumulus,代码行数:18,代码来源:sftp.py

示例8: open_gateway

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
    def open_gateway(self):
        """
        Obtain a socket-like object from `gateway`.

        :returns:
            A ``direct-tcpip`` `paramiko.channel.Channel`, if `gateway` was a
            `.Connection`; or a `~paramiko.proxy.ProxyCommand`, if `gateway`
            was a string.

        .. versionadded:: 2.0
        """
        # ProxyCommand is faster to set up, so do it first.
        if isinstance(self.gateway, string_types):
            # Leverage a dummy SSHConfig to ensure %h/%p/etc are parsed.
            # TODO: use real SSH config once loading one properly is
            # implemented.
            ssh_conf = SSHConfig()
            dummy = "Host {}\n    ProxyCommand {}"
            ssh_conf.parse(StringIO(dummy.format(self.host, self.gateway)))
            return ProxyCommand(ssh_conf.lookup(self.host)["proxycommand"])
        # Handle inner-Connection gateway type here.
        # TODO: logging
        self.gateway.open()
        # TODO: expose the opened channel itself as an attribute? (another
        # possible argument for separating the two gateway types...) e.g. if
        # someone wanted to piggyback on it for other same-interpreter socket
        # needs...
        # TODO: and the inverse? allow users to supply their own socket/like
        # object they got via $WHEREEVER?
        # TODO: how best to expose timeout param? reuse general connection
        # timeout from config?
        return self.gateway.transport.open_channel(
            kind="direct-tcpip",
            dest_addr=(self.host, int(self.port)),
            # NOTE: src_addr needs to be 'empty but not None' values to
            # correctly encode into a network message. Theoretically Paramiko
            # could auto-interpret None sometime & save us the trouble.
            src_addr=("", 0),
        )
开发者ID:fabric,项目名称:fabric,代码行数:41,代码来源:connection.py

示例9: main

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def main(working_dir=None, cmd='', group_name='AWS'):
    """
    Main function for the module. Calls other functions according to the parameters provided.
    """
    constants.set_working_dir(working_dir)
    constants.set_account_key(None)
    constants.set_logentries_logging()
      
    if working_dir is None:
        ssh_config_name = 'ssh_config'
    else:
        ssh_config_name = '%s/ssh_config'%working_dir

    env.use_ssh_config = True
    try:
        config_file = file(ssh_config_name)
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)
        env._ssh_config = config

    list_hosts = []
    for host_config in env._ssh_config._config:
        host_name = host_config['host'][0]
        if host_config['host'][0]!='*':
            ssh_config = host_config['config']['hostname']
            logger.info('Found instance ssh config. instance=%s, ssh_config=%s', host_name, ssh_config)
            list_hosts.extend(host_config['host'])

    if cmd == 'deprovision':
        execute(deprovision,hosts=list_hosts)
    elif cmd == 'clean':
        execute(set_instance_host_keys,hosts=list_hosts)
        execute(remove_hosts,group_name,hosts=list_hosts)
    elif cmd == '':
        execute(sync,hosts=list_hosts)
开发者ID:StephenHynes7,项目名称:le_aws,代码行数:40,代码来源:sync_log.py

示例10: annotate_from_sshconfig

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def annotate_from_sshconfig(env):
    """
    Adds support for reading the host names, users and ports from ~/ssh/config

    Replaces the hosts defined in ssh config with actual host names, so that Fabric
    can take the advantage from it

    .. IMPORTANT:: This does not support /etc/ssh/ssh_config yet!

    """
    from os.path import expanduser
    from paramiko.config import SSHConfig

    def hostinfo(host, config):
        hive = config.lookup(host)
        if "hostname" in hive:
            host = hive["hostname"]
        if "user" in hive:
            host = "%[email protected]%s" % (hive["user"], host)
        if "port" in hive:
            host = "%s:%s" % (host, hive["port"])
        return host

    # Look for user config, if found, parse it and update roledefs. Otherwise just ignore it (it is not required at all)
    try:
        config_file = file(expanduser("~/.ssh/config"))
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)
        keys = [config.lookup(host).get("identityfile", None) for host in api.env.hosts]
        env.key_filename = [expanduser(key) for key in keys if key is not None]
        env.hosts = [hostinfo(host, config) for host in env.hosts]

        for role, rolehosts in env.roledefs.items():
            env.roledefs[role] = [hostinfo(host, config) for host in rolehosts]
开发者ID:nagyistoce,项目名称:trac-multiproject,代码行数:39,代码来源:base.py

示例11: _annotate_hosts_with_ssh_config_info

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
    def _annotate_hosts_with_ssh_config_info():
        from os.path import expanduser
        from paramiko.config import SSHConfig

        def hostinfo(host, config):
            hive = config.lookup(host)
            if "hostname" in hive:
                host = hive["hostname"]
            if "user" in hive:
                host = "%[email protected]%s" % (hive["user"], host)
            if "port" in hive:
                host = "%s:%s" % (host, hive["port"])
            return host

        try:
            config_file = file(expanduser("~/.ssh/config"))
        except IOError:
            pass
        else:
            config = SSHConfig()
            config.parse(config_file)
            keys = [config.lookup(host).get("identityfile", None) for host in env.hosts]
            env.key_filename = [expanduser(key) for key in keys if key is not None]
            env.hosts = [hostinfo(host, config) for host in env.hosts]
开发者ID:bennomadic,项目名称:django-coop,代码行数:26,代码来源:fabfile.py

示例12: _annotate_hosts_with_ssh_config_info

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
def _annotate_hosts_with_ssh_config_info(path):
    from os.path import expanduser
    from paramiko.config import SSHConfig

    def hostinfo(host, config):
        hive = config.lookup(host)
        # if 'hostname' in hive:
           # host = hive['hostname']
        if 'user' in hive:
            host = '%[email protected]%s' % (hive['user'], host)
        if 'port' in hive:
            host = '%s:%s' % (host, hive['port'])
        #print 'hive',hive
        #print 'host',host
        return host

    try:
        config_file = file(expanduser(path))
    except IOError:
        pass
    else:
        config = SSHConfig()
        config.parse(config_file)

        # add hosts from ssh config to env.host & sort + unique
        env.hosts.extend([h for h in config.get_hostnames() if len(h) > 1])
        env.hosts = sorted(set(env.hosts))

        keys = [config.lookup(host).get('identityfile', None) for host in env.hosts]
        # flatten
        keys = [item for sublist in keys  if sublist is not None for item in sublist]
        env.key_filename = [expanduser(key) for key in keys if key is not None]
        env.hosts = [hostinfo(host, config) for host in env.hosts]

        for role, rolehosts in env.roledefs.items():
            env.roledefs[role] = [hostinfo(host, config) for host in rolehosts]
开发者ID:epcim,项目名称:fabfile,代码行数:38,代码来源:__init__.py

示例13: SshClient

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
class SshClient(object):

    def __init__(self, containers_file, extra_ssh_config_file):

        with open(conf.containers_file()) as infile:
            containers = yaml.load(infile)

        self._containers = []
        self._container_default_config = {}

        self._ssh_config = SSHConfig()
        if extra_ssh_config_file is not None:
            with open(extra_ssh_config_file) as ssh_config_file:
                self._ssh_config.parse(ssh_config_file)

        self._missing_host_key_policy = AutoAddPolicy()

        for container_config in containers:
            if container_config['Host'] == '*':
                self._container_default_config = container_config
                break

        for container_config in containers:
            if container_config['Host'] == '*':
                continue

            container_host = container_config['Host']

            ip_address = self._get_hostname_option(container_config)

            container = {
                'Hostname': container_host,
                'Id': container_host,
                'Name': container_host,
                'Labels': {
                    'interface': container_config['Interface'],
                    'type': container_config['Type']
                },
                'State': {
                    'Running': 'running'
                },
                'NetworkSettings': {
                    'IPAddress': ip_address,
                    'MacAddress': None,
                    'Ports': None
                },
                'Config': container_config
            }
            self._containers.append(container)

        self.next_exec_id = 0
        self.ssh_connections = {}
        self.execs = {}

    def inspect_container(self, container_id):
        for container in self._containers:
            if container_id == container['Id']:
                return {'Name': container['Name'],
                        'Config': container,
                        'State': container['State'],
                        'NetworkSettings': container['NetworkSettings']}
        return None

    def containers(self, all=None):
        return self._containers

    def get_container_by_name(self, container_name):
        for container in self._containers:
            if container_name == str(container['Name']).translate(None, '/'):
                return container
        return None

    def exec_create(self, container_name,
                    cmd,
                    stdout=True,
                    stderr=True,
                    tty=False):
        LOG.info("Running command %s at container %s " % (cmd, container_name))
        exec_id = self.next_exec_id
        self.next_exec_id += 1
        self.execs[exec_id] = (container_name, cmd, None, None)
        return exec_id

    def exec_start(self, exec_id, detach=False, stream=False):
        container_name, cmd, stdout, stderr = self.execs[exec_id]
        ssh_connection = self._get_ssh_connection(container_name)
        stdin, stdout, stderr = ssh_connection.exec_command(cmd)
        if stream:
            self.execs[exec_id] = (container_name, cmd, stdout, stderr)
            return stdout
        else:
            return ''.join(stdout.readlines())

    def exec_inspect(self, exec_id, detach=False, stream=False):
        container_name, cmd, stdout, stderr = self.execs[exec_id]

        if stdout.channel.exit_status_ready():
            running = False
            exit_code = stdout.channel.recv_exit_status()
        else:
#.........这里部分代码省略.........
开发者ID:midonet,项目名称:midonet,代码行数:103,代码来源:ssh.py

示例14: SystemVM

# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import parse [as 别名]
class SystemVM(object):
    def __init__(self, host="default", vagrantDir=None, controlVagrant=True):
        global _defaultVagrantDir
        self.host = host
        self._controlVagrant = controlVagrant
        if vagrantDir is None:
            vagrantDir = _defaultVagrantDir
        self._vagrant = Vagrant(root=vagrantDir)
        self._startedVagrant = False
        self._sshClient = None
        self._sshConfigStr = None
        self._sshConfig = None
        self._sshHostConfig = None

    def maybeUp(self):
        if not self._controlVagrant:
            return
        state = self._vagrant.status(vm_name=self.host)[0].state
        if state == Vagrant.NOT_CREATED:
            self._vagrant.up(vm_name=self.host)
            self._startedVagrant = True
        elif state in [Vagrant.POWEROFF, Vagrant.SAVED, Vagrant.ABORTED]:
            raise Exception("SystemVM testing does not support resume(), do not use vagrant suspend/halt")
        elif state == Vagrant.RUNNING:
            self._startedVagrant = False
        else:
            raise Exception("Unrecognized vagrant state %s" % state)

    def maybeDestroy(self):
        if not self._controlVagrant or not self._startedVagrant:
            return
        self._vagrant.destroy(vm_name=self.host)
        if self._sshClient is not None:
            self._sshClient.close()

    def loadSshConfig(self):
        if self._sshConfig is None:
            self._sshConfigStr = self._vagrant.ssh_config(vm_name=self.host)
            configObj = StringIO(self._sshConfigStr)
            self._sshConfig = SSHConfig()
            # noinspection PyTypeChecker
            self._sshConfig.parse(configObj)
            self._sshHostConfig = self._sshConfig.lookup(self.host)

    @property
    def sshConfig(self):
        if self._sshConfig is None:
            self.loadSshConfig()
        return self._sshConfig

    @property
    def sshConfigStr(self):
        if self._sshConfigStr is None:
            self.loadSshConfig()
        return self._sshConfigStr

    @property
    def sshClient(self):
        if self._sshClient is None:
            self.loadSshConfig()
            self._sshClient = SSHClient()
            self._sshClient.set_missing_host_key_policy(AutoAddPolicy())
            self._sshClient.connect(self.hostname, self.sshPort, self.sshUser, key_filename=self.sshKey, timeout=10)
        return self._sshClient

    @property
    def hostname(self):
        return self._sshHostConfig.get("hostname", self.host)

    @property
    def sshPort(self):
        return int(self._sshHostConfig.get("port", 22))

    @property
    def sshUser(self):
        return self._sshHostConfig.get("user", "root")

    @property
    def sshKey(self):
        return self._sshHostConfig.get("identityfile", "~/.ssh/id_rsa")
开发者ID:tianshangjun,项目名称:cloudstack,代码行数:82,代码来源:__init__.py


注:本文中的paramiko.config.SSHConfig.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。