本文整理汇总了Python中paramiko.config.SSHConfig.lookup方法的典型用法代码示例。如果您正苦于以下问题:Python SSHConfig.lookup方法的具体用法?Python SSHConfig.lookup怎么用?Python SSHConfig.lookup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko.config.SSHConfig
的用法示例。
在下文中一共展示了SSHConfig.lookup方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _annotate_hosts_with_ssh_config_info
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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]
示例2: annotate_hosts_with_ssh_config_info
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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]
示例3: getSSHInfoForHost
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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
示例4: ssh_config
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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)
示例5: __init__
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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
示例6: open_gateway
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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),
)
示例7: annotate_from_sshconfig
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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]
示例8: _annotate_hosts_with_ssh_config_info
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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]
示例9: _annotate_hosts_with_ssh_config_info
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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]
示例10: SshClient
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [as 别名]
#.........这里部分代码省略.........
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:
running = True
exit_code = "N/A"
return {'Running': running,
'ProcessConfig': {
'entrypoint': cmd.split(' ')[0],
'arguments': cmd.split(' ')[1:]},
'ExitCode': exit_code}
def _get_option(self, container_config, option, paramiko_option, default):
return container_config.get(option,
self._container_default_config.get(option,
self._ssh_config.lookup(container_config['Host']).get(paramiko_option,
default)))
def _get_hostname_option(self, container_config):
hostname = self._get_option(container_config, 'HostName', 'hostname', 'localhost')
return socket.gethostbyname(hostname)
def _get_port_option(self, container_config):
return int(self._get_option(container_config, 'Port', 'port', '22'))
def _get_user_option(self, container_config):
return self._get_option(container_config, 'User', 'user', 'root')
def _get_password_option(self, container_config):
return self._get_option(container_config, 'Password', 'password', None)
def _get_identity_file_option(self, container_config):
return self._get_option(container_config, 'IdentityFile', 'identityfile', '/dev/null')
def _get_strict_host_key_checking_option(self, container_config):
return self._get_option(container_config, 'StrictHostKeyChecking',
'stricthostkeychecking', 'yes')
def _get_user_known_hosts_file(self, container_config):
return self._get_option(container_config, 'UserKnownHostsFile',
'userknownhostsfile', '/dev/null')
def _get_ssh_connection(self, container_name):
if container_name in self.ssh_connections:
return self.ssh_connections[container_name]
config = self.get_container_by_name(container_name)['Config']
ssh_connection = paramiko.SSHClient()
ssh_connection.load_system_host_keys()
ssh_connection.set_missing_host_key_policy(self._missing_host_key_policy)
try:
ssh_connection.connect(self._get_hostname_option(config),
port=self._get_port_option(config),
username=self._get_user_option(config),
password=self._get_password_option(config),
key_filename=self._get_identity_file_option(config),
look_for_keys=False,
allow_agent=False
)
except paramiko.ssh_exception.AuthenticationException:
raise Exception("AuthenticationException while trying to " +
("connect to %s container: %s with config %s" %
(container_name, container_name, config)))
self.ssh_connections[container_name] = ssh_connection
return self.ssh_connections[container_name]
示例11: SystemVM
# 需要导入模块: from paramiko.config import SSHConfig [as 别名]
# 或者: from paramiko.config.SSHConfig import lookup [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")