Executes a command and returns its output. If the command's return code is non-zero or the command times out, an exception is raised.
(self, cmd, cmd_prepend="set -euo pipefail\n", timeout_secs=None)
| 81 | atexit.register(self.close) |
| 82 | |
| 83 | def shell(self, cmd, cmd_prepend="set -euo pipefail\n", timeout_secs=None): |
| 84 | """Executes a command and returns its output. If the command's return code is |
| 85 | non-zero or the command times out, an exception is raised. |
| 86 | """ |
| 87 | cmd = textwrap.dedent(cmd.strip()) |
| 88 | if cmd_prepend: |
| 89 | cmd = cmd_prepend + cmd |
| 90 | LOG.debug("Running command via ssh on %s:\n%s" % (self.host_name, cmd)) |
| 91 | transport = self.get_transport() |
| 92 | for is_first_attempt in (True, False): |
| 93 | try: |
| 94 | channel = transport.open_session() |
| 95 | break |
| 96 | except Exception as e: |
| 97 | if is_first_attempt: |
| 98 | LOG.warn("Error opening ssh session: %s" % e) |
| 99 | self.close() |
| 100 | self.connect(self.host_name, **self.connect_kwargs) |
| 101 | else: |
| 102 | raise Exception("Unable to open ssh session to %s: %s" % (self.host_name, e)) |
| 103 | channel.set_combine_stderr(True) |
| 104 | channel.exec_command(cmd) |
| 105 | process = RemoteProcess(channel) |
| 106 | |
| 107 | deadline = time.time() + timeout_secs if timeout_secs is not None else None |
| 108 | while True: |
| 109 | retcode = process.poll() |
| 110 | if retcode is not None or (deadline and time.time() > deadline): |
| 111 | break |
| 112 | time.sleep(0.1) |
| 113 | |
| 114 | if retcode == 0: |
| 115 | return process.stdout.read().decode("utf-8").encode("ascii", errors="ignore") |
| 116 | if retcode is None: |
| 117 | if process.channel.recv_ready(): |
| 118 | output = process.channel.recv(None) |
| 119 | else: |
| 120 | output = "" |
| 121 | if process.channel.recv_stderr_ready(): |
| 122 | err = process.channel.recv_stderr(None) |
| 123 | else: |
| 124 | err = "" |
| 125 | else: |
| 126 | output = process.stdout.read() |
| 127 | err = process.stderr.read() |
| 128 | if output: |
| 129 | output = output.decode("utf-8").encode("ascii", errors="ignore") |
| 130 | else: |
| 131 | output = "(No stdout)" |
| 132 | if err: |
| 133 | err = err.decode("utf-8").encode("ascii", errors="ignore") |
| 134 | else: |
| 135 | err = "(No stderr)" |
| 136 | if retcode is None: |
| 137 | raise Timeout("Command timed out after %s seconds\ncmd: %s\nstdout: %s\nstderr: %s" |
| 138 | % (timeout_secs, cmd, output, err)) |
| 139 | raise Exception(("Command returned non-zero exit code: %s" |
| 140 | "\ncmd: %s\nstdout: %s\nstderr: %s") % (retcode, cmd, output, err)) |