add option to connect to non-standard ssh port
[yardstick.git] / yardstick / ssh.py
1 # Copyright 2013: Mirantis Inc.
2 # All Rights Reserved.
3 #
4 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
5 #    not use this file except in compliance with the License. You may obtain
6 #    a copy of the License at
7 #
8 #         http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #    Unless required by applicable law or agreed to in writing, software
11 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 #    License for the specific language governing permissions and limitations
14 #    under the License.
15
16 # yardstick comment: this is a modified copy of rally/rally/common/sshutils.py
17
18 """High level ssh library.
19
20 Usage examples:
21
22 Execute command and get output:
23
24     ssh = sshclient.SSH("root", "example.com", port=33)
25     status, stdout, stderr = ssh.execute("ps ax")
26     if status:
27         raise Exception("Command failed with non-zero status.")
28     print stdout.splitlines()
29
30 Execute command with huge output:
31
32     class PseudoFile(object):
33         def write(chunk):
34             if "error" in chunk:
35                 email_admin(chunk)
36
37     ssh = sshclient.SSH("root", "example.com")
38     ssh.run("tail -f /var/log/syslog", stdout=PseudoFile(), timeout=False)
39
40 Execute local script on remote side:
41
42     ssh = sshclient.SSH("user", "example.com")
43     status, out, err = ssh.execute("/bin/sh -s arg1 arg2",
44                                    stdin=open("~/myscript.sh", "r"))
45
46 Upload file:
47
48     ssh = sshclient.SSH("user", "example.com")
49     ssh.run("cat > ~/upload/file.gz", stdin=open("/store/file.gz", "rb"))
50
51 Eventlet:
52
53     eventlet.monkey_patch(select=True, time=True)
54     or
55     eventlet.monkey_patch()
56     or
57     sshclient = eventlet.import_patched("opentstack.common.sshclient")
58
59 """
60
61 import select
62 import socket
63 import time
64
65 import paramiko
66 from scp import SCPClient
67 import six
68 import logging
69
70 LOG = logging.getLogger(__name__)
71
72 DEFAULT_PORT = 22
73
74
75 class SSHError(Exception):
76     pass
77
78
79 class SSHTimeout(SSHError):
80     pass
81
82
83 class SSH(object):
84     """Represent ssh connection."""
85
86     def __init__(self, user, host, port=DEFAULT_PORT, pkey=None,
87                  key_filename=None, password=None):
88         """Initialize SSH client.
89
90         :param user: ssh username
91         :param host: hostname or ip address of remote ssh server
92         :param port: remote ssh port
93         :param pkey: RSA or DSS private key string or file object
94         :param key_filename: private key filename
95         :param password: password
96         """
97
98         self.user = user
99         self.host = host
100         # we may get text port from YAML, convert to int
101         self.port = int(port)
102         self.pkey = self._get_pkey(pkey) if pkey else None
103         self.password = password
104         self.key_filename = key_filename
105         self._client = False
106
107     def _get_pkey(self, key):
108         if isinstance(key, six.string_types):
109             key = six.moves.StringIO(key)
110         errors = []
111         for key_class in (paramiko.rsakey.RSAKey, paramiko.dsskey.DSSKey):
112             try:
113                 return key_class.from_private_key(key)
114             except paramiko.SSHException as e:
115                 errors.append(e)
116         raise SSHError("Invalid pkey: %s" % (errors))
117
118     def _get_client(self):
119         if self._client:
120             return self._client
121         try:
122             self._client = paramiko.SSHClient()
123             self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
124             self._client.connect(self.host, username=self.user,
125                                  port=self.port, pkey=self.pkey,
126                                  key_filename=self.key_filename,
127                                  password=self.password,
128                                  allow_agent=False, look_for_keys=False,
129                                  timeout=1)
130             return self._client
131         except Exception as e:
132             message = ("Exception %(exception_type)s was raised "
133                        "during connect. Exception value is: %(exception)r")
134             self._client = False
135             raise SSHError(message % {"exception": e,
136                                       "exception_type": type(e)})
137
138     def close(self):
139         self._client.close()
140         self._client = False
141
142     def run(self, cmd, stdin=None, stdout=None, stderr=None,
143             raise_on_error=True, timeout=3600):
144         """Execute specified command on the server.
145
146         :param cmd:             Command to be executed.
147         :param stdin:           Open file or string to pass to stdin.
148         :param stdout:          Open file to connect to stdout.
149         :param stderr:          Open file to connect to stderr.
150         :param raise_on_error:  If False then exit code will be return. If True
151                                 then exception will be raized if non-zero code.
152         :param timeout:         Timeout in seconds for command execution.
153                                 Default 1 hour. No timeout if set to 0.
154         """
155
156         client = self._get_client()
157
158         if isinstance(stdin, six.string_types):
159             stdin = six.moves.StringIO(stdin)
160
161         return self._run(client, cmd, stdin=stdin, stdout=stdout,
162                          stderr=stderr, raise_on_error=raise_on_error,
163                          timeout=timeout)
164
165     def _run(self, client, cmd, stdin=None, stdout=None, stderr=None,
166              raise_on_error=True, timeout=3600):
167
168         transport = client.get_transport()
169         session = transport.open_session()
170         session.exec_command(cmd)
171         start_time = time.time()
172
173         data_to_send = ""
174         stderr_data = None
175
176         # If we have data to be sent to stdin then `select' should also
177         # check for stdin availability.
178         if stdin and not stdin.closed:
179             writes = [session]
180         else:
181             writes = []
182
183         while True:
184             # Block until data can be read/write.
185             r, w, e = select.select([session], writes, [session], 1)
186
187             if session.recv_ready():
188                 data = session.recv(4096)
189                 LOG.debug("stdout: %r" % data)
190                 if stdout is not None:
191                     stdout.write(data)
192                 continue
193
194             if session.recv_stderr_ready():
195                 stderr_data = session.recv_stderr(4096)
196                 LOG.debug("stderr: %r" % stderr_data)
197                 if stderr is not None:
198                     stderr.write(stderr_data)
199                 continue
200
201             if session.send_ready():
202                 if stdin is not None and not stdin.closed:
203                     if not data_to_send:
204                         data_to_send = stdin.read(4096)
205                         if not data_to_send:
206                             stdin.close()
207                             session.shutdown_write()
208                             writes = []
209                             continue
210                     sent_bytes = session.send(data_to_send)
211                     # LOG.debug("sent: %s" % data_to_send[:sent_bytes])
212                     data_to_send = data_to_send[sent_bytes:]
213
214             if session.exit_status_ready():
215                 break
216
217             if timeout and (time.time() - timeout) > start_time:
218                 args = {"cmd": cmd, "host": self.host}
219                 raise SSHTimeout("Timeout executing command "
220                                  "'%(cmd)s' on host %(host)s" % args)
221             if e:
222                 raise SSHError("Socket error.")
223
224         exit_status = session.recv_exit_status()
225         if 0 != exit_status and raise_on_error:
226             fmt = "Command '%(cmd)s' failed with exit_status %(status)d."
227             details = fmt % {"cmd": cmd, "status": exit_status}
228             if stderr_data:
229                 details += " Last stderr data: '%s'." % stderr_data
230             raise SSHError(details)
231         return exit_status
232
233     def execute(self, cmd, stdin=None, timeout=3600):
234         """Execute the specified command on the server.
235
236         :param cmd:     Command to be executed.
237         :param stdin:   Open file to be sent on process stdin.
238         :param timeout: Timeout for execution of the command.
239
240         :returns: tuple (exit_status, stdout, stderr)
241         """
242         stdout = six.moves.StringIO()
243         stderr = six.moves.StringIO()
244
245         exit_status = self.run(cmd, stderr=stderr,
246                                stdout=stdout, stdin=stdin,
247                                timeout=timeout, raise_on_error=False)
248         stdout.seek(0)
249         stderr.seek(0)
250         return (exit_status, stdout.read(), stderr.read())
251
252     def wait(self, timeout=120, interval=1):
253         """Wait for the host will be available via ssh."""
254         start_time = time.time()
255         while True:
256             try:
257                 return self.execute("uname")
258             except (socket.error, SSHError) as e:
259                 LOG.debug("Ssh is still unavailable: %r" % e)
260                 time.sleep(interval)
261             if time.time() > (start_time + timeout):
262                 raise SSHTimeout("Timeout waiting for '%s'" % self.host)
263
264     def put(self, files, remote_path=b'.', recursive=False):
265         client = self._get_client()
266
267         with SCPClient(client.get_transport()) as scp:
268             scp.put(files, remote_path, recursive)
269
270     # keep shell running in the background, e.g. screen
271     def send_command(self, command):
272         client = self._get_client()
273         client.exec_command(command, get_pty=True)