wktdev

wktdev

How to use SSH to log into machine , get a file and download it to the users download folder

Like the title suggest, the code below renders an html link and when the user clicks it an event creates an SSH connection to log into another server, grab a file and download the file to the users download folder.

If there is an easier way to do this please let me know.

The code below partially works but there are two problems.

Problem 1. When the user clicks the link, the file downloads as expected, but if the user clicks it again, it doesn’t work unless the page is refreshed. I assume this might be fixable with a redirect of some sort, but nothing I’ve done seems to work.

Problem 2. I get this error and I am not sure how to proceed as I do not understand it.

[error] Ranch listener AppWeb.Endpoint.HTTP had connection process started with :cowboy_clear:start_link/4 at #PID<0.1027.0> exit with reason: {:function_clause, [{:cowboy_http, :commands, [{:state, #PID<0.602.0>, AppWeb.Endpoint.HTTP, #Port<0.63>, :ranch_tcp, :undefined, %{env: %{dispatch: [{:_, [], [{:_, [], Plug.Cowboy.Handler, {Phoenix.Endpoint.SyncCodeReloadPlug, {AppWeb.Endpoint, []}}}]}]}, stream_handlers: [:cowboy_telemetry_h, :cowboy_stream_h]}, "", %{}, {{10, 26, 10, 126}, 50238}, {{172, 30, 0, 95}, 80}, :undefined, #Reference<0.4223096848.725614593.72607>, true, 6, {:ps_request_line, 0}, 65535, 5, :done, 1000, [{:stream, 5, {:cowboy_telemetry_h, {:state, {:cowboy_stream_h, {:state, :undefined, AppWeb.Endpoint.HTTP, #PID<0.1093.0>, :undefined, :undefined, :undefined, :undefined, 0, :nofin, "", 0, ...}}, #Function<0.39451584/1 in :cowboy_telemetry_h.metrics_callback>, :undefined, %{body_length: 0, cert: :undefined, has_body: false, headers: %{"accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "accept-encoding" => "gzip, deflate", "accept-language" => "en-US,en;q=0.9", "connection" => "keep-alive", "cookie" => "_app_key=SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYZ3hoNWVWdFhOVFh6ZzFudGoydWkxV0dC.VRdSr3lkxk5STVLYbfaG5n9X9kZdDyN1DmT7896_5I4", "host" => "kraal-dev.bndge.com", "referer" => "http://kraal-dev.bndge.com/sims", ...}, host: "kraal-dev.bndge.com", method: "GET", path: "/download", peer: {{10, 26, ...}, 50238}, pid: #PID<0.1027.0>, port: 80, qs: "", ...}, "302 Found", %{"cache-control" => "max-age=0, private, must-revalidate", "content-length" => "150", "content-type" => "text/html; charset=utf-8", "date" => "Mon, 10 Jun 2024 17:59:38 GMT", "location" => "/sims/", "referrer-policy" => "strict-origin-when-cross-origin", "server" => "Cowboy", "x-content-type-options" => "nosniff", "x-download-options" => "noopen", ...}, AppWeb.Endpoint.HTTP, -576457459844398761, :undefined, :undefined, :undefined, -576457459731708161, -576457459731708161, %{#PID<0.1093.0> => %{...}}, [], ...}}, "GET", :"HTTP/1.1", :undefined, :undefined, 0, []}], [{:child, #PID<0.1093.0>, 5, 5000, :undefined}]}, 5, [{:response, "302 Found", %{"cache-control" => "max-age=0, private, must-revalidate", "content-length" => "150", "content-type" => "text/html; charset=utf-8", "date" => "Mon, 10 Jun 2024 17:59:38 GMT", "location" => "/sims/", "referrer-policy" => "strict-origin-when-cross-origin", "server" => "Cowboy", "x-content-type-options" => "nosniff", "x-download-options" => "noopen", "x-frame-options" => "SAMEORIGIN", "x-permitted-cross-domain-policies" => "none", "x-request-id" => "F9e2cRGhBIE2zqsAAARR"}, [["<html><body>You are being <a href=\"/sims/\">redirected</a>."], "<iframe hidden height=\"0\" width=\"0\" src=\"/phoenix/live_reload/frame\"></iframe>", "</body>" | "</html>"]}]], [file: '/home/wturner/sandbox/testbed/app/deps/cowboy/src/cowboy_http.erl', line: 957]}, {:cowboy_http, :loop, 1, [file: '/home/wturner/sandbox/testbed/app/deps/cowboy/src/cowboy_http.erl', line: 257]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 240]}]}


Thank you, the code is below:

Code

Liveview named sims_live.ex

defmodule AppWeb.SimsLive do
  use AppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok,
     assign(socket,
       nothing: ""
     )}
  end


  def handle_event("get_JSON", params, socket) do

    IO.inspect params

    {:ok, conn} =
      SSH.connect(
        "system_ip.whatever",
        user: "root",
        identity: "/.ssh/id_rsa_nop",
        save_accepted_host: false,
        silently_accept_hosts: true,
        user_interaction: false
      )
     file_path = "priv/data.json"

    result = SSH.fetch(conn, "/data.json")

    {:ok, json_data} = result

    case File.write(file_path, json_data) do
      :ok ->
        # IO.puts("File written successfully")
        {:noreply, redirect(socket, to: "/download")}

      {:error, reason} ->
        IO.puts("Failed to write to file: #{reason}")
        {:noreply, socket}
    end

  end


  def render(assigns) do
    ~H"""
    <div>


          <a phx-click="get_JSON"> Click me </a>



    </div>
    """
  end
end

Controller named download_controller

defmodule AppWeb.DownloadController do
  use AppWeb, :controller

  def home(conn, _params) do

    path = Application.app_dir(:app, "priv/data.json") #static directory
    send_download(conn, {:file, path})

    render(conn, :home, layout: false)

  end
end

Marked As Solved

wktdev

wktdev

I solved the problem by writing code that creates a different relationship between the controller and Live View. I cleared out all the Live View code and rendered a simple item list. Clicking an item launches a dead view controller. The controller contained all my SSH code, File manipulation code and download code. This approach works.

Last Post!

D4no0

D4no0

Honestly that SSH elixir library is a bit strange, because if you want file transfer it would make sense to do that over SFTP. OTP has a good client already implemented for that: ssh_sftp — OTP 29.0.2 (ssh 6.0.1)

Where Next?

Popular in Questions Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31494 112
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

We're in Beta

About us Mission Statement