Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a command via SSH in Elixir?

Tags:

ssh

elixir

I know I can open a ssh connection to a remote server:

:ssh.start
:ssh.connect("11.22.33.44", 22, user: "my_login123")

But how can I actually send a command and receive a response from it? I don't mean the interactive mode, I want to just send a command and receive a reply.

like image 533
Kumakaja Avatar asked Sep 20 '25 01:09

Kumakaja


2 Answers

It might just be easier to use an Elixir library such as SSHex as this actually uses the erlang :ssh library but provides a much nicer interface as well as making it simpler to accomplish what you are after.

E.g. From the readme

{:ok, conn} = SSHEx.connect ip: '123.123.123.123', user: 'myuser'

SSHEx.cmd! conn, 'mkdir -p /path/to/newdir'
res = SSHEx.cmd! conn, 'ls /some/path'

Where the value of res will be the response from the command

EDIT However, if you are set on using :ssh. Then you would need to use the :ssh_connection modules exec command which takes in the :ssh connection as a parameter.

See this link here for more detail on how to do this.

like image 109
Harrison Lucas Avatar answered Sep 21 '25 16:09

Harrison Lucas


Here is an example that uses only :ssh and no external libraries. To run it you will need to have public key login set up on your target host. For more information, read the Erlang SSH User's Guide.

ssh-connect.exs

#! /usr/bin/env elixir
:ssh.start()
{:ok, conn} = :ssh.connect('raspi', 22,
  silently_accept_hosts: true,
  user: System.get_env("USER") |> to_charlist(),
  user_dir: Path.join(System.user_home!(), ".ssh") |> to_charlist(),
  user_interaction: false,
)
{:ok, chan} = :ssh_connection.session_channel(conn, :infinity)
:success = :ssh_connection.exec(conn, chan, 'uname -a', :infinity)
for _ <- 0..3 do
  receive do
    {:ssh_cm, ^conn, value} -> IO.inspect(value)
  end  
end
:ok = :ssh.close(conn)

Sample output

{:data, 0, 0, "Linux raspberrypi 4.4.50+ #970 Mon Feb 20 19:12:50 GMT 2017 armv6l GNU/Linux\n"}
{:eof, 0}
{:exit_status, 0, 0}
{:closed, 0}
like image 45
nwk Avatar answered Sep 21 '25 18:09

nwk