Skip to content

Instantly share code, notes, and snippets.

@sepbot
Created February 14, 2020 23:30
Show Gist options
  • Save sepbot/ec57a3398c18548eb3ea328d1f2f2821 to your computer and use it in GitHub Desktop.
Save sepbot/ec57a3398c18548eb3ea328d1f2f2821 to your computer and use it in GitHub Desktop.
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