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.
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.
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.
#! /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)
{: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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With