本文整理汇总了Python中paramiko.SSHConfig方法的典型用法代码示例。如果您正苦于以下问题:Python paramiko.SSHConfig方法的具体用法?Python paramiko.SSHConfig怎么用?Python paramiko.SSHConfig使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko
的用法示例。
在下文中一共展示了paramiko.SSHConfig方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: credentials
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例2: get_ssh_key_for_host
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例3: open
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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)
示例4: get_a_ssh_config
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
# ------------------------------
示例5: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例6: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例7: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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)
示例8: client
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例9: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例10: _get_ssh_config_for_host
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例11: scp_upload
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例12: sshinfo
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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
示例13: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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)
示例14: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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]
示例15: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHConfig [as 别名]
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)