1 # Copyright 2013: Mirantis Inc.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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
16 # yardstick comment: this is a modified copy of rally/rally/common/sshutils.py
18 """High level ssh library.
22 Execute command and get output:
24 ssh = sshclient.SSH("root", "example.com", port=33)
25 status, stdout, stderr = ssh.execute("ps ax")
27 raise Exception("Command failed with non-zero status.")
28 print stdout.splitlines()
30 Execute command with huge output:
32 class PseudoFile(object):
37 ssh = sshclient.SSH("root", "example.com")
38 ssh.run("tail -f /var/log/syslog", stdout=PseudoFile(), timeout=False)
40 Execute local script on remote side:
42 ssh = sshclient.SSH("user", "example.com")
43 status, out, err = ssh.execute("/bin/sh -s arg1 arg2",
44 stdin=open("~/myscript.sh", "r"))
48 ssh = sshclient.SSH("user", "example.com")
49 ssh.run("cat > ~/upload/file.gz", stdin=open("/store/file.gz", "rb"))
53 eventlet.monkey_patch(select=True, time=True)
55 eventlet.monkey_patch()
57 sshclient = eventlet.import_patched("opentstack.common.sshclient")
66 from scp import SCPClient
70 LOG = logging.getLogger(__name__)
73 class SSHError(Exception):
77 class SSHTimeout(SSHError):
82 """Represent ssh connection."""
84 def __init__(self, user, host, port=22, pkey=None,
85 key_filename=None, password=None):
86 """Initialize SSH client.
88 :param user: ssh username
89 :param host: hostname or ip address of remote ssh server
90 :param port: remote ssh port
91 :param pkey: RSA or DSS private key string or file object
92 :param key_filename: private key filename
93 :param password: password
99 self.pkey = self._get_pkey(pkey) if pkey else None
100 self.password = password
101 self.key_filename = key_filename
104 def _get_pkey(self, key):
105 if isinstance(key, six.string_types):
106 key = six.moves.StringIO(key)
108 for key_class in (paramiko.rsakey.RSAKey, paramiko.dsskey.DSSKey):
110 return key_class.from_private_key(key)
111 except paramiko.SSHException as e:
113 raise SSHError("Invalid pkey: %s" % (errors))
115 def _get_client(self):
119 self._client = paramiko.SSHClient()
120 self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
121 self._client.connect(self.host, username=self.user,
122 port=self.port, pkey=self.pkey,
123 key_filename=self.key_filename,
124 password=self.password,
125 allow_agent=False, look_for_keys=False,
128 except Exception as e:
129 message = ("Exception %(exception_type)s was raised "
130 "during connect. Exception value is: %(exception)r")
132 raise SSHError(message % {"exception": e,
133 "exception_type": type(e)})
139 def run(self, cmd, stdin=None, stdout=None, stderr=None,
140 raise_on_error=True, timeout=3600):
141 """Execute specified command on the server.
143 :param cmd: Command to be executed.
144 :param stdin: Open file or string to pass to stdin.
145 :param stdout: Open file to connect to stdout.
146 :param stderr: Open file to connect to stderr.
147 :param raise_on_error: If False then exit code will be return. If True
148 then exception will be raized if non-zero code.
149 :param timeout: Timeout in seconds for command execution.
150 Default 1 hour. No timeout if set to 0.
153 client = self._get_client()
155 if isinstance(stdin, six.string_types):
156 stdin = six.moves.StringIO(stdin)
158 return self._run(client, cmd, stdin=stdin, stdout=stdout,
159 stderr=stderr, raise_on_error=raise_on_error,
162 def _run(self, client, cmd, stdin=None, stdout=None, stderr=None,
163 raise_on_error=True, timeout=3600):
165 transport = client.get_transport()
166 session = transport.open_session()
167 session.exec_command(cmd)
168 start_time = time.time()
173 # If we have data to be sent to stdin then `select' should also
174 # check for stdin availability.
175 if stdin and not stdin.closed:
181 # Block until data can be read/write.
182 r, w, e = select.select([session], writes, [session], 1)
184 if session.recv_ready():
185 data = session.recv(4096)
186 LOG.debug("stdout: %r" % data)
187 if stdout is not None:
191 if session.recv_stderr_ready():
192 stderr_data = session.recv_stderr(4096)
193 LOG.debug("stderr: %r" % stderr_data)
194 if stderr is not None:
195 stderr.write(stderr_data)
198 if session.send_ready():
199 if stdin is not None and not stdin.closed:
201 data_to_send = stdin.read(4096)
204 session.shutdown_write()
207 sent_bytes = session.send(data_to_send)
208 # LOG.debug("sent: %s" % data_to_send[:sent_bytes])
209 data_to_send = data_to_send[sent_bytes:]
211 if session.exit_status_ready():
214 if timeout and (time.time() - timeout) > start_time:
215 args = {"cmd": cmd, "host": self.host}
216 raise SSHTimeout("Timeout executing command "
217 "'%(cmd)s' on host %(host)s" % args)
219 raise SSHError("Socket error.")
221 exit_status = session.recv_exit_status()
222 if 0 != exit_status and raise_on_error:
223 fmt = "Command '%(cmd)s' failed with exit_status %(status)d."
224 details = fmt % {"cmd": cmd, "status": exit_status}
226 details += " Last stderr data: '%s'." % stderr_data
227 raise SSHError(details)
230 def execute(self, cmd, stdin=None, timeout=3600):
231 """Execute the specified command on the server.
233 :param cmd: Command to be executed.
234 :param stdin: Open file to be sent on process stdin.
235 :param timeout: Timeout for execution of the command.
237 :returns: tuple (exit_status, stdout, stderr)
239 stdout = six.moves.StringIO()
240 stderr = six.moves.StringIO()
242 exit_status = self.run(cmd, stderr=stderr,
243 stdout=stdout, stdin=stdin,
244 timeout=timeout, raise_on_error=False)
247 return (exit_status, stdout.read(), stderr.read())
249 def wait(self, timeout=120, interval=1):
250 """Wait for the host will be available via ssh."""
251 start_time = time.time()
254 return self.execute("uname")
255 except (socket.error, SSHError) as e:
256 LOG.debug("Ssh is still unavailable: %r" % e)
258 if time.time() > (start_time + timeout):
259 raise SSHTimeout("Timeout waiting for '%s'" % self.host)
261 def put(self, files, remote_path=b'.', recursive=False):
262 client = self._get_client()
264 with SCPClient(client.get_transport()) as scp:
265 scp.put(files, remote_path, recursive)
267 # keep shell running in the background, e.g. screen
268 def send_command(self, command):
269 client = self._get_client()
270 client.exec_command(command, get_pty=True)