automatic deploy a wholeset of TestAPI ecosystem
[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, username, password=None, jumphost=None):
20     client = None
21     try:
22         if jumphost is None:
23             client = paramiko.SSHClient()
24         else:
25             client = JumpHostHopClient()
26             client.configure_jump_host(jumphost['ip'],
27                                        jumphost['username'],
28                                        jumphost['password'])
29
30         if client is None:
31             raise Exception('Could not connect to client')
32
33         client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
34         client.connect(hostname,
35                        username=username,
36                        password=password)
37         return client
38     except Exception, e:
39         logger.error(e)
40         return None
41
42
43 def get_file(ssh_conn, src, dest):
44     try:
45         sftp = ssh_conn.open_sftp()
46         sftp.get(src, dest)
47         return True
48     except Exception, e:
49         logger.error("Error [get_file(ssh_conn, '%s', '%s']: %s" %
50                      (src, dest, e))
51         return None
52
53
54 def put_file(ssh_conn, src, dest):
55     try:
56         sftp = ssh_conn.open_sftp()
57         sftp.put(src, dest)
58         return True
59     except Exception, e:
60         logger.error("Error [put_file(ssh_conn, '%s', '%s']: %s" %
61                      (src, dest, e))
62         return None
63
64
65 class JumpHostHopClient(paramiko.SSHClient):
66     '''
67     Connect to a remote server using a jumphost hop
68     '''
69
70     def __init__(self, *args, **kwargs):
71         self.logger = OPNFVLogger.Logger("JumpHostHopClient").getLogger()
72         self.jumphost_ssh = None
73         self.jumphost_transport = None
74         self.jumphost_channel = None
75         self.jumphost_ip = None
76         self.jumphost_ssh_key = None
77         self.local_ssh_key = os.path.join(os.getcwd(), 'id_rsa')
78         super(JumpHostHopClient, self).__init__(*args, **kwargs)
79
80     def configure_jump_host(self, jh_ip, jh_user, jh_pass,
81                             jh_ssh_key='/root/.ssh/id_rsa'):
82         self.jumphost_ip = jh_ip
83         self.jumphost_ssh_key = jh_ssh_key
84         self.jumphost_ssh = paramiko.SSHClient()
85         self.jumphost_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
86         self.jumphost_ssh.connect(jh_ip,
87                                   username=jh_user,
88                                   password=jh_pass)
89         self.jumphost_transport = self.jumphost_ssh.get_transport()
90
91     def connect(self, hostname, port=22, username='root', password=None,
92                 pkey=None, key_filename=None, timeout=None, allow_agent=True,
93                 look_for_keys=True, compress=False, sock=None, gss_auth=False,
94                 gss_kex=False, gss_deleg_creds=True, gss_host=None,
95                 banner_timeout=None):
96         try:
97             if self.jumphost_ssh is None:
98                 raise Exception('You must configure the jump '
99                                 'host before calling connect')
100
101             get_file_res = get_file(self.jumphost_ssh,
102                                     self.jumphost_ssh_key,
103                                     self.local_ssh_key)
104             if get_file_res is None:
105                 raise Exception('Could\'t fetch SSH key from jump host')
106             jumphost_key = (paramiko.RSAKey
107                             .from_private_key_file(self.local_ssh_key))
108
109             self.jumphost_channel = self.jumphost_transport.open_channel(
110                 "direct-tcpip",
111                 (hostname, 22),
112                 (self.jumphost_ip, 22))
113
114             self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
115             super(JumpHostHopClient, self).connect(hostname,
116                                                    username=username,
117                                                    pkey=jumphost_key,
118                                                    sock=self.jumphost_channel)
119             os.remove(self.local_ssh_key)
120         except Exception, e:
121             self.logger.error(e)