本文整理汇总了Python中paramiko.SSHConfig类的典型用法代码示例。如果您正苦于以下问题:Python SSHConfig类的具体用法?Python SSHConfig怎么用?Python SSHConfig使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SSHConfig类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_openssh_config
def read_openssh_config(host, config_file=None):
"""Parses user's OpenSSH config for per hostname configuration for
hostname, user, port and private key values
:param host: Hostname to lookup in config
"""
_ssh_config_file = config_file if config_file else \
os.path.sep.join([os.path.expanduser('~'), '.ssh', 'config'])
# Load ~/.ssh/config if it exists to pick up username
# and host address if set
if not os.path.isfile(_ssh_config_file):
return
ssh_config = SSHConfig()
ssh_config.parse(open(_ssh_config_file))
host_config = ssh_config.lookup(host)
host = (host_config['hostname'] if
'hostname' in host_config
else host)
user = host_config['user'] if 'user' in host_config else None
port = int(host_config['port']) if 'port' in host_config else 22
pkey = None
# Try configured keys, pick first one that loads
if 'identityfile' in host_config:
for file_name in host_config['identityfile']:
pkey = load_private_key(file_name)
if pkey:
break
return host, user, port, pkey
示例2: __init__
def __init__(self, hostname='localhost', username=None, password=None,
config_path='~/.ssh/config', port=None, verbose=False):
if not hostname:
raise ValueError('Missing hostname')
self.sftp = None
self.ssh = None
ssh_config_path = path(config_path).expand()
if not username:
config = SSHConfig()
if ssh_config_path.exists():
config.parse(ssh_config_path.open())
if config.lookup(hostname):
host_config = config.lookup(hostname)
username = host_config['user']
else:
print 'Unknown host ', hostname
else: print 'config file path wrong'
self.verbose = verbose
if not username:
username = getpass.getuser()
if self.verbose:
print 'Connection info: ', username, hostname, ssh_config_path
#self.ssh.set_missing_host_key_policy(
# paramiko.AutoAddPolicy())
self.hostname = hostname
self.username = username
self.password = password
self.connect()
示例3: readsshconfig
def readsshconfig(self):
config = os.path.expanduser('~/.ssh/config')
if not os.path.exists(config):
return
f = open(config,'r')
sshconfig = SSHConfig()
sshconfig.parse(f)
f.close()
host = self.host
try:
host,port = host.split(':')
except:
port = None
opt = sshconfig.lookup(host)
if port is None:
port = opt.get('port')
host = opt.get('hostname', host)
if port:
host = "%s:%s" % (host,port)
self.host=host
if not self.identityfile:
self.identityfile = opt.get('identityfile', None)
if self.identityfile:
self.identityfile = os.path.expanduser(self.identityfile).strip()
if not self.user:
self.user=opt.get('user','root')
示例4: __init__
def __init__(self, hostname):
""" Initialise and connect to SSH. """
super(GerritSSHClient, self).__init__()
self.load_system_host_keys()
self.remote_version = None
configfile = expanduser("~/.ssh/config")
if not isfile(configfile):
raise GerritError("ssh config file '%s' does not exist" %
configfile)
config = SSHConfig()
config.parse(open(configfile))
data = config.lookup(hostname)
if not data:
raise GerritError("No ssh config for host %s" % hostname)
if not 'hostname' in data or not 'port' in data or not 'user' in data:
raise GerritError("Missing configuration data in %s" % configfile)
key_filename = None
if 'identityfile' in data:
key_filename = abspath(expanduser(data['identityfile']))
if not isfile(key_filename):
raise GerritError("Identity file '%s' does not exist" %
key_filename)
try:
port = int(data['port'])
except ValueError:
raise GerritError("Invalid port: %s" % data['port'])
try:
self.connect(hostname=data['hostname'],
port=port,
username=data['user'],
key_filename=key_filename)
except socket.error as e:
raise GerritError("Failed to connect to server: %s" % e)
示例5: main
def main():
USAGE = "usage: %prog [options] host1:path1 host2:path2"
parser = OptionParser(usage=USAGE)
parser.add_option("-F", "--config-file",
action="store",
dest="config_file",
default="%s/.ssh/config" % os.environ['HOME'],
help="SSH config file (default: ~/.ssh/config)",)
parser.add_option("--scp-options",
action="store",
dest="scp_options",
default="",
help="string of options (in quotes) passed directy to the scp command",)
(options, args) = parser.parse_args()
host1, path1 = args[0].split(':', 1)
host2, path2 = args[1].split(':', 1)
# ssh config file
config = SSHConfig()
config.parse(open(options.config_file))
o = config.lookup(host2)
# copy keyfile
keyfile_remote = '/tmp/%s' % os.path.basename(o['identityfile'])
run('scp %s %s:%s' % (o['identityfile'], host1, keyfile_remote))
# copy actual file
ssh_options = ' -o'.join(['='.join([k, v]) for k, v in o.iteritems()
if k != 'hostname' and k != 'identityfile'])
if ssh_options:
ssh_options = '-o' + ssh_options
run('ssh %s scp %s -i %s -oStrictHostKeyChecking=no %s %s %s:%s' % (
host1, options.scp_options, keyfile_remote, ssh_options, path1,
o['hostname'], path2))
示例6: start_procs
def start_procs(serial, hosts, starter_func, wait=0.0):
config = SSHConfig()
config.parse(open(os.path.expanduser('~/.ssh/config')))
try:
wait = float(wait)
except ValueError:
pass
processes = []
for host in hosts:
process = starter_func(host, config.lookup(host))
process.start()
if serial or wait > 0.0:
process.join()
if isinstance(wait, Number):
sleep(wait)
processes.append(process)
while multiprocessing.active_children():
try:
sleep(0.3)
except KeyboardInterrupt:
for p in processes:
p.stop()
break
return processes
示例7: connect
def connect(self, timeout=None):
'''
Setup the connection to remote SSH servers
'''
if self._connections is not None:
raise RuntimeError('already connected')
ssh_config = SSHConfig()
ssh_config_file = os.path.sep.join(
[os.path.expanduser('~'),
'.ssh',
'config'])
if os.path.isfile(ssh_config_file):
ssh_config.parse(open(ssh_config_file))
self._connections = [SSHClient() for _ in self._host]
for conn, host, port in zip(self._connections, self._host, self._port):
self._pool.spawn(self._connect, conn, host, port, ssh_config)
try:
self._pool.join(timeout, raise_error=True)
except:
self._pool.kill(None)
for conn in self._connections:
try:
conn.close()
except:
pass
self._connections = None
示例8: _configure
def _configure(self):
""" Configure the ssh parameters from the config file. """
configfile = expanduser("~/.ssh/config")
if not isfile(configfile):
raise GerritError("ssh config file '%s' does not exist" %
configfile)
config = SSHConfig()
config.parse(open(configfile))
data = config.lookup(self.hostname)
if not data:
raise GerritError("No ssh config for host %s" % self.hostname)
if 'hostname' not in data or 'port' not in data or 'user' not in data:
raise GerritError("Missing configuration data in %s" % configfile)
self.hostname = data['hostname']
self.username = data['user']
if 'identityfile' in data:
key_filename = abspath(expanduser(data['identityfile'][0]))
if not isfile(key_filename):
raise GerritError("Identity file '%s' does not exist" %
key_filename)
self.key_filename = key_filename
try:
self.port = int(data['port'])
except ValueError:
raise GerritError("Invalid port: %s" % data['port'])
if 'proxycommand' in data:
self.proxy = ProxyCommand(data['proxycommand'])
示例9: read_ssh_config
def read_ssh_config(self, hostname):
config_file = os.path.join(os.getenv('HOME'), '.ssh/config')
config = SSHConfig()
config.parse(open(config_file, 'r'))
self.ssh_config = config.lookup(hostname)
if len(self.ssh_config.keys()) < 2:
print("Hostname no found in .ssh/config")
示例10: lookup
def lookup(configfile):
config = SSHConfig()
config.parse(open(configfile))
res = config.lookup(login)
if res.get('user'):
res['username'] = res['user']
del res['user']
return res
示例11: _configure
def _configure(self):
"""
Configure the ssh parameters from the config file.
The Port and username are extracted from .ssh/config, unless
overridden by arguments to the constructor.
If username and or port are provided to `__init__`, they will
override the values found in the configuration file.
:raise:
SSHException under the following conditions:
* No configuration file is found
* It does not contain an entry for the Host.
* It references a keyfile which does not exist
* The port number is non-numeric or negative
* Values for port and username can not be determined
"""
configfile = expanduser("~/.ssh/config")
if not isfile(configfile):
raise SSHException("ssh config file '%s' does not exist" %
configfile)
config = SSHConfig()
config.parse(open(configfile))
data = config.lookup(self.hostname)
if not data:
raise SSHException("No ssh config for host %s" % self.hostname)
self.hostname = data.get('hostname', None)
self.proxy_cmd = data.get('proxycommand', None)
if not self.username:
self.username = data.get('user', None)
if self.key_filename:
self.key_filename = abspath(expanduser(self.key_filename))
elif 'identityfile' in data:
self.key_filename = abspath(expanduser(data['identityfile'][0]))
if self.key_filename and not isfile(self.key_filename):
raise SSHException("Identity file '%s' does not exist" %
self.key_filename)
if self.port is None:
try:
self.port = int(data.get('port', '29418'))
except ValueError:
raise SSHException("Invalid port: %s" % data['port'])
config_data = (self.hostname, self.port, self.username)
if not all(config_data):
raise SSHException("Missing configuration data in %s" % configfile)
示例12: scp
def scp(self, filename, remote_path):
config = SSHConfig()
config.parse(open(os.path.expanduser('~/.ssh/config')))
o = config.lookup('geodata')
ssh_client = SSHClient()
ssh_client.load_system_host_keys()
ssh_client.connect(o['hostname'], username=o['user'])
scp = SCPClient(ssh_client.get_transport())
scp.put(filename, remote_path=remote_path)
示例13: __init__
def __init__(self, host):
# store the host
self.host = host
# read the ssh config file
config = SSHConfig()
fname = os.path.join(os.environ['HOME'], '.ssh', 'config')
config.parse(open(fname))
self.config = config.lookup(host)
示例14: get_ssh_config
def get_ssh_config(path=None):
"""
Return a ssh configuration parsed from path.
:param path: The path to the config to parse.
"""
path = path or '%s/%s' % (os.environ.get('HOME'), '.ssh/config')
fh = open(path)
ssh = SSHConfig()
ssh.parse(fh)
return ssh
示例15: config
def config(self):
sshconfig = SSHConfig()
try:
sshconfig.parse(open(SSH_CONFIG))
except IOError:
sys.stderr.write("Warning: SSH config file location invalid.\n")
conf = sshconfig.lookup(self.server)
if 'port' in conf:
conf['port'] = int(conf['port'])
return conf