1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 # Authors: George Paraskevopoulos (geopar@intracom-telecom.com)
4 # Jose Lausuch (jose.lausuch@ericsson.com)
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
15 from opnfv.utils import opnfv_logger as logger
17 logger = logger.Logger("SSH utils").getLogger()
20 def get_ssh_client(hostname,
28 client = paramiko.SSHClient()
30 client = ProxyHopClient()
31 client.configure_jump_host(proxy['ip'],
35 raise Exception('Could not connect to client')
37 client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
38 if pkey_file is not None:
39 key = paramiko.RSAKey.from_private_key_file(pkey_file)
40 client.load_system_host_keys()
41 client.connect(hostname,
45 client.connect(hostname,
55 def get_file(ssh_conn, src, dest):
57 sftp = ssh_conn.open_sftp()
61 logger.error("Error [get_file(ssh_conn, '%s', '%s']: %s" %
66 def put_file(ssh_conn, src, dest):
68 sftp = ssh_conn.open_sftp()
72 logger.error("Error [put_file(ssh_conn, '%s', '%s']: %s" %
77 class ProxyHopClient(paramiko.SSHClient):
79 Connect to a remote server using a proxy hop
82 def __init__(self, *args, **kwargs):
84 self.proxy_transport = None
85 self.proxy_channel = None
87 self.proxy_ssh_key = None
88 self.local_ssh_key = os.path.join(os.getcwd(), 'id_rsa')
89 super(ProxyHopClient, self).__init__(*args, **kwargs)
91 def configure_jump_host(self, jh_ip, jh_user, jh_pass,
92 jh_ssh_key='/root/.ssh/id_rsa'):
94 self.proxy_ssh_key = jh_ssh_key
95 self.proxy_ssh = paramiko.SSHClient()
96 self.proxy_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
97 self.proxy_ssh.connect(jh_ip,
100 self.proxy_transport = self.proxy_ssh.get_transport()
102 def connect(self, hostname, port=22, username='root', password=None,
103 pkey=None, key_filename=None, timeout=None, allow_agent=True,
104 look_for_keys=True, compress=False, sock=None, gss_auth=False,
105 gss_kex=False, gss_deleg_creds=True, gss_host=None,
106 banner_timeout=None):
108 if self.proxy_ssh is None:
109 raise Exception('You must configure the jump '
110 'host before calling connect')
112 get_file_res = get_file(self.proxy_ssh,
115 if get_file_res is None:
116 raise Exception('Could\'t fetch SSH key from jump host')
117 proxy_key = (paramiko.RSAKey
118 .from_private_key_file(self.local_ssh_key))
120 self.proxy_channel = self.proxy_transport.open_channel(
125 self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
126 super(ProxyHopClient, self).connect(hostname,
129 sock=self.proxy_channel)
130 os.remove(self.local_ssh_key)