Created
February 14, 2020 23:30
-
-
Save sepbot/ec57a3398c18548eb3ea328d1f2f2821 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Test do | |
# runs command and logs outputs when they become available, mostly useful for long running commands that | |
# provide incremental output as the command progresses | |
def run_command_and_log!(host, conn, command) do | |
res = Enum.reduce( | |
SSHEx.stream(conn, command, channel_timeout: 10_000, exec_timeout: 3_600_000), | |
%{:status => nil,:stdout => [], :stderr => []}, | |
fn (x, acc) -> | |
case x do | |
{:stdout, row} -> | |
Logger.info("#{host} - stdout - #{row}") | |
lines = [String.split(row, ~r/\R/)] ++ acc[:stdout] | |
%{acc | :stdout => lines} | |
{:stderr, row} -> | |
Logger.info("#{host} - stderr - #{row}") | |
lines = [String.split(row, ~r/\R/)] ++ acc[:stderr] | |
%{acc | :stderr => lines} | |
{:status, status} -> %{acc | :status => status} | |
{:error, reason} -> raise reason | |
end | |
end | |
) | |
if res[:status] == 0 do | |
%{ | |
:stdout => res[:stdout] |> Enum.reverse |> List.flatten |> Enum.join("\n"), | |
:stderr => res[:stderr] |> Enum.reverse |> List.flatten |> Enum.join("\n"), | |
} | |
else | |
raise "command #{command} failed: stderr: #{res[:stderr]} stdout: #{res[:stdout]}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment