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

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement