blob: f43ebd919a03e94f176c5df024a03c886b9a8a65 [file] [log] [blame]
Daryl Walleck1465d612011-11-02 02:22:15 -05001import time
2import socket
3import warnings
Daryl Walleck6b9b2882012-04-08 21:43:39 -05004from tempest import exceptions
Daryl Walleck1465d612011-11-02 02:22:15 -05005
6with warnings.catch_warnings():
7 warnings.simplefilter("ignore")
8 import paramiko
9
10
11class Client(object):
12
Daryl Walleck6b9b2882012-04-08 21:43:39 -050013 def __init__(self, host, username, password, timeout=60):
Daryl Walleck1465d612011-11-02 02:22:15 -050014 self.host = host
15 self.username = username
16 self.password = password
17 self.timeout = int(timeout)
18
19 def _get_ssh_connection(self):
20 """Returns an ssh connection to the specified host"""
21 _timeout = True
22 ssh = paramiko.SSHClient()
23 ssh.set_missing_host_key_policy(
24 paramiko.AutoAddPolicy())
25 _start_time = time.time()
26
27 while not self._is_timed_out(self.timeout, _start_time):
28 try:
29 ssh.connect(self.host, username=self.username,
Daryl Walleck6b9b2882012-04-08 21:43:39 -050030 password=self.password, timeout=20)
Daryl Walleck1465d612011-11-02 02:22:15 -050031 _timeout = False
32 break
33 except socket.error:
34 continue
35 except paramiko.AuthenticationException:
36 time.sleep(15)
37 continue
38 if _timeout:
Daryl Walleck6b9b2882012-04-08 21:43:39 -050039 raise exceptions.SSHTimeout(host=self.host,
40 user=self.username,
41 password=self.password)
Daryl Walleck1465d612011-11-02 02:22:15 -050042 return ssh
43
44 def _is_timed_out(self, timeout, start_time):
45 return (time.time() - timeout) > start_time
46
47 def connect_until_closed(self):
48 """Connect to the server and wait until connection is lost"""
49 try:
50 ssh = self._get_ssh_connection()
51 _transport = ssh.get_transport()
52 _start_time = time.time()
53 _timed_out = self._is_timed_out(self.timeout, _start_time)
54 while _transport.is_active() and not _timed_out:
55 time.sleep(5)
56 _timed_out = self._is_timed_out(self.timeout, _start_time)
57 ssh.close()
58 except (EOFError, paramiko.AuthenticationException, socket.error):
59 return
60
61 def exec_command(self, cmd):
62 """Execute the specified command on the server.
63
64 :returns: data read from standard output of the command
65
66 """
67 ssh = self._get_ssh_connection()
68 stdin, stdout, stderr = ssh.exec_command(cmd)
69 output = stdout.read()
70 ssh.close()
71 return output
72
73 def test_connection_auth(self):
74 """ Returns true if ssh can connect to server"""
75 try:
76 connection = self._get_ssh_connection()
77 connection.close()
78 except paramiko.AuthenticationException:
79 return False
80
81 return True