Automatic Deployment
[genesis.git] / fuel / deploy / cloud_deploy / ssh_client.py
1 import paramiko
2 from cloud import common
3
4 TIMEOUT = 600
5 LOG = common.LOG
6
7 class SSHClient(object):
8
9     def __init__(self, host, username, password):
10         self.host = host
11         self.username = username
12         self.password = password
13         self.client = None
14
15     def open(self, timeout=TIMEOUT):
16         self.client = paramiko.SSHClient()
17         self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
18         self.client.connect(self.host, username=self.username,
19                             password=self.password, timeout=timeout)
20
21     def close(self):
22         if self.client is not None:
23             self.client.close()
24             self.client = None
25
26     def execute(self, command, sudo=False, timeout=TIMEOUT):
27         if sudo and self.username != 'root':
28             command = "sudo -S -p '' %s" % command
29         stdin, stdout, stderr = self.client.exec_command(command,
30                                                          timeout=timeout)
31         if sudo:
32             stdin.write(self.password + '\n')
33             stdin.flush()
34         return ''.join(''.join(stderr.readlines()) +
35                        ''.join(stdout.readlines()))
36
37     def run(self, command):
38         transport = self.client.get_transport()
39         transport.set_keepalive(1)
40         chan = transport.open_session()
41         chan.exec_command(command)
42
43         while not chan.exit_status_ready():
44             if chan.recv_ready():
45                 data = chan.recv(1024)
46                 while data:
47                     print data
48                     data = chan.recv(1024)
49
50             if chan.recv_stderr_ready():
51                 error_buff = chan.recv_stderr(1024)
52                 while error_buff:
53                     print error_buff
54                     error_buff = chan.recv_stderr(1024)
55         exit_status = chan.recv_exit_status()
56         LOG.debug('Exit status %s' % exit_status)