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