[deployment_handler] Remove current scripts
[releng.git] / modules / opnfv / utils / SSHUtils.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 paramiko
13 import opnfv.utils.OPNFVLogger as OPNFVLogger
14 import os
15
16 logger = OPNFVLogger.Logger('SSHUtils').getLogger()
17
18
19 def get_ssh_client(hostname,
20                    username,
21                    password=None,
22                    proxy=None,
23                    pkey_file=None):
24     client = None
25     try:
26         if proxy is None:
27             client = paramiko.SSHClient()
28         else:
29             client = ProxyHopClient()
30             client.configure_jump_host(proxy['ip'],
31                                        proxy['username'],
32                                        proxy['password'])
33         if client is None:
34             raise Exception('Could not connect to client')
35
36         client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
37         if pkey_file is not None:
38             key = paramiko.RSAKey.from_private_key_file(pkey_file)
39             client.load_system_host_keys()
40             client.connect(hostname,
41                            username=username,
42                            pkey=key)
43         else:
44             client.connect(hostname,
45                            username=username,
46                            password=password)
47
48         return client
49     except Exception, e:
50         logger.error(e)
51         return None
52
53
54 def get_file(ssh_conn, src, dest):
55     try:
56         sftp = ssh_conn.open_sftp()
57         sftp.get(src, dest)
58         return True
59     except Exception, e:
60         logger.error("Error [get_file(ssh_conn, '%s', '%s']: %s" %
61                      (src, dest, e))
62         return None
63
64
65 def put_file(ssh_conn, src, dest):
66     try:
67         sftp = ssh_conn.open_sftp()
68         sftp.put(src, dest)
69         return True
70     except Exception, e:
71         logger.error("Error [put_file(ssh_conn, '%s', '%s']: %s" %
72                      (src, dest, e))
73         return None
74
75
76 class ProxyHopClient(paramiko.SSHClient):
77     '''
78     Connect to a remote server using a proxy hop
79     '''
80
81     def __init__(self, *args, **kwargs):
82         self.logger = OPNFVLogger.Logger("ProxyHopClient").getLogger()
83         self.proxy_ssh = None
84         self.proxy_transport = None
85         self.proxy_channel = None
86         self.proxy_ip = 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)
90
91     def configure_jump_host(self, jh_ip, jh_user, jh_pass,
92                             jh_ssh_key='/root/.ssh/id_rsa'):
93         self.proxy_ip = jh_ip
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,
98                                username=jh_user,
99                                password=jh_pass)
100         self.proxy_transport = self.proxy_ssh.get_transport()
101
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):
107         try:
108             if self.proxy_ssh is None:
109                 raise Exception('You must configure the jump '
110                                 'host before calling connect')
111
112             get_file_res = get_file(self.proxy_ssh,
113                                     self.proxy_ssh_key,
114                                     self.local_ssh_key)
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))
119
120             self.proxy_channel = self.proxy_transport.open_channel(
121                 "direct-tcpip",
122                 (hostname, 22),
123                 (self.proxy_ip, 22))
124
125             self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
126             super(ProxyHopClient, self).connect(hostname,
127                                                 username=username,
128                                                 pkey=proxy_key,
129                                                 sock=self.proxy_channel)
130             os.remove(self.local_ssh_key)
131         except Exception, e:
132             self.logger.error(e)