Use Phoenix to SSH into a Server and Download a File to Users Local Machine
From ElixirBlocks
Download_Controller
defmodule AppWeb.DownloadController do use AppWeb, :controller def home(conn, %{"switch" => switch}) do {:ok, conn} = SSH.connect( # "sim.com.whatever" user: "root", identity: "/home/user/.ssh/id_rsa_nop", save_accepted_host: false, silently_accept_hosts: true, user_interaction: false ) file_path = "priv/test.json" {:ok, json_data} = conn case File.write(file_path, json_data) do :ok -> IO.puts("File written successfully") path = Application.app_dir(:app, "priv/test.json") #static directory send_download(conn, {:file, path}) render(conn, :home, layout: false) {:error, reason} -> IO.puts("Failed to write to file: #{reason}") end render(conn, :home, layout: false) end end
LiveView
defmodule AppWeb.SimsLive do use AppWeb, :live_view def mount(_params, _session, socket) do {:ok, assign(socket, switches: ["sim-x", "sim-y", "sim-z"])} end def render(assigns) do ~H""" <ul> <%= for switch <- @switches do %> <a href={"/download/#{switch}"}><li><%=switch%></li></a> <% end %> </ul> """ end end