4c5ff5c1ba50252f65f0df0507718ddffc726300
[releng.git] / modules / opnfv / utils / ssh_utils.py
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 ##############################################################################
10
11
12 import os
13 import paramiko
14
15 from opnfv.utils import opnfv_logger as logger
16
17 logger = logger.Logger("SSH utils").getLogger()
18 SSH_TIMEOUT = 60
19
20 ''' Monkey Patch paramiko _custom_start_client '''
21 # We are using paramiko 2.1.1 and in the CI in the SFC
22 # test we are facing this issue:
23 # https://github.com/robotframework/SSHLibrary/issues/158
24 # The fix was merged in paramiko 2.1.3 in this PR:
25 # https://github.com/robotframework/SSHLibrary/pull/159/files
26 # Until we upgrade we can use this monkey patch to work
27 # around the issue
28
29
30 def _custom_start_client(self, *args, **kwargs):
31     self.banner_timeout = 45
32     self._orig_start_client(*args, **kwargs)
33
34
35 paramiko.transport.Transport._orig_start_client = \
36     paramiko.transport.Transport.start_client
37 paramiko.transport.Transport.start_client = _custom_start_client
38 ''' Monkey Patch paramiko _custom_start_client '''
39
40
41 def get_ssh_client(hostname,
42                    username,
43                    password=None,
44                    proxy=None,
45                    pkey_file=None):
46     client = None
47     try:
48         if proxy is None:
49             client = paramiko.SSHClient()
50         else:
51             client = ProxyHopClient()
52             client.configure_jump_host(proxy['ip'],
53                                        proxy['username'],
54                                        proxy['password'])
55         if client is None:
56             raise Exception('Could not connect to client')
57
58         client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
59         if pkey_file is not None:
60             key = paramiko.RSAKey.from_private_key_file(pkey_file)
61             client.load_system_host_keys()
62             client.connect(hostname,
63                            username=username,
64                            pkey=key,
65                            timeout=SSH_TIMEOUT)
66         else:
67             client.connect(hostname,
68                            username=username,
69                            password=password,
70                            timeout=SSH_TIMEOUT)
71
72         return client
73     except Exception as e:
74         logger.error(e)
75         return None
76
77
78 def get_file(ssh_conn, src, dest):
79     try:
80         sftp = ssh_conn.open_sftp()
81         sftp.get(src, dest)
82         return True
83     except Exception as e:
84         logger.error("Error [get_file(ssh_conn, '%s', '%s']: %s" %
85                      (src, dest, e))
86         return None
87
88
89 def put_file(ssh_conn, src, dest):
90     try:
91         sftp = ssh_conn.open_sftp()
92         sftp.put(src, dest)
93         return True
94     except Exception as e:
95         logger.error("Error [put_file(ssh_conn, '%s', '%s']: %s" %
96                      (src, dest, e))
97         return None
98
99
100 class ProxyHopClient(paramiko.SSHClient):
101     '''
102     Connect to a remote server using a proxy hop
103     '''
104
105     def __init__(self, *args, **kwargs):
106         self.proxy_ssh = None
107         self.proxy_transport = None
108         self.proxy_channel = None
109         self.proxy_ip = None
110         self.proxy_ssh_key = None
111         self.local_ssh_key = os.path.join(os.getcwd(), 'id_rsa')
112         super(ProxyHopClient, self).__init__(*args, **kwargs)
113
114     def configure_jump_host(self, jh_ip, jh_user, jh_pass,
115                             jh_ssh_key='/root/.ssh/id_rsa'):
116         self.proxy_ip = jh_ip
117         self.proxy_ssh_key = jh_ssh_key
118         self.proxy_ssh = paramiko.SSHClient()
119         self.proxy_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
120         self.proxy_ssh.connect(jh_ip,
121                                username=jh_user,
122                                password=jh_pass,
123                                timeout=SSH_TIMEOUT)
124         self.proxy_transport = self.proxy_ssh.get_transport()
125
126     def connect(self, hostname, port=22, username='root', password=None,
127                 pkey=None, key_filename=None, timeout=None, allow_agent=True,
128                 look_for_keys=True, compress=False, sock=None, gss_auth=False,
129                 gss_kex=False, gss_deleg_creds=True, gss_host=None,
130                 banner_timeout=None):
131         try:
132             if self.proxy_ssh is None:
133                 raise Exception('You must configure the jump '
134                                 'host before calling connect')
135
136             get_file_res = get_file(self.proxy_ssh,
137                                     self.proxy_ssh_key,
138                                     self.local_ssh_key)
139             if get_file_res is None:
140                 raise Exception('Could\'t fetch SSH key from jump host')
141             proxy_key = (paramiko.RSAKey
142                          .from_private_key_file(self.local_ssh_key))
143
144             self.proxy_channel = self.proxy_transport.open_channel(
145                 "direct-tcpip",
146                 (hostname, 22),
147                 (self.proxy_ip, 22))
148
149             self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
150             super(ProxyHopClient, self).connect(hostname,
151                                                 username=username,
152                                                 pkey=proxy_key,
153                                                 sock=self.proxy_channel,
154                                                 timeout=timeout)
155             os.remove(self.local_ssh_key)
156         except Exception as e:
157             logger.error(e)