Autodeploy inspired on Prototype #2
[genesis.git] / fuel / deploy / ssh_client.py
1 import paramiko
2 import common
3 import scp
4
5 TIMEOUT = 600
6 log = common.log
7 err = common.err
8
9 class SSHClient(object):
10
11     def __init__(self, host, username, password):
12         self.host = host
13         self.username = username
14         self.password = password
15         self.client = None
16
17     def open(self, timeout=TIMEOUT):
18         self.client = paramiko.SSHClient()
19         self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
20         self.client.connect(self.host, username=self.username,
21                             password=self.password, timeout=timeout)
22
23     def close(self):
24         if self.client is not None:
25             self.client.close()
26             self.client = None
27
28     def __enter__(self):
29         self.open()
30         return self
31
32     def __exit__(self, type, value, traceback):
33         self.close()
34
35     def exec_cmd(self, command, sudo=False, timeout=TIMEOUT, check=True):
36         if sudo and self.username != 'root':
37             command = "sudo -S -p '' %s" % command
38         stdin, stdout, stderr = self.client.exec_command(command,
39                                                          timeout=timeout)
40         if sudo:
41             stdin.write(self.password + '\n')
42             stdin.flush()
43         response = stdout.read().strip()
44         error = stderr.read().strip()
45
46         if check:
47             if error:
48                 self.close()
49                 err(error)
50             else:
51                 return response
52         return response, error
53
54     def run(self, command):
55         transport = self.client.get_transport()
56         transport.set_keepalive(1)
57         chan = transport.open_session()
58         chan.exec_command(command)
59         while not chan.exit_status_ready():
60             if chan.recv_ready():
61                 data = chan.recv(1024)
62                 while data:
63                     print data
64                     data = chan.recv(1024)
65
66             if chan.recv_stderr_ready():
67                 error_buff = chan.recv_stderr(1024)
68                 while error_buff:
69                     print error_buff
70                     error_buff = chan.recv_stderr(1024)
71         exit_status = chan.recv_exit_status()
72         log('Exit status %s' % exit_status)
73
74     def scp_get(self, remote, local='.', dir=False):
75         try:
76             with scp.SCPClient(self.client.get_transport()) as _scp:
77                 _scp.get(remote, local, dir)
78         except Exception as e:
79             err(e)
80
81     def scp_put(self, local, remote='.', dir=False):
82         try:
83             with scp.SCPClient(self.client.get_transport()) as _scp:
84                 _scp.put(local, remote, dir)
85         except Exception as e:
86             err(e)