suzuzusu日記

(´・ω・`)

SSH in Elixir

ElixirでSSHをする方法を忘備録として書いておく.

iexして以下を実行する

iex(1)> ip = '1.2.3.4'
'1.2.3.4'
iex(2)> port = 22
22
iex(3)> ssh_config = [
...(3)>   user: 'user',
...(3)>   password: 'password1234',
...(3)>   silently_accept_hosts: true
...(3)> ]
[user: 'user', password: 'password1234', silently_accept_hosts: true]
iex(4)> :ssh.start
:ok
iex(5)> :ssh.shell(ip, port, ssh_config)
remote > # login

command実行の場合

iex(1)> ip = '1.2.3.4'
'1.2.3.4'
iex(2)> port = 22
22
iex(3)> ssh_config = [
...(3)>   user: 'user',
...(3)>   password: 'password1234',
...(3)>   silently_accept_hosts: true
...(3)> ]
[user: 'user', password: 'password1234', silently_accept_hosts: true]
iex(4)> :ssh.start
:ok
iex(5)> {:ok, con_ref} = :ssh.connect(ip, port, ssh_config)
{:ok, #PID<0.128.0>}
iex(6)> {ok, ch_id} =  :ssh_connection.session_channel(con_ref, :infinity)
{:ok, 0}
iex(7)> :ssh_connection.exec(con_ref, ch_id, "date", :infinity)
:success
iex(8)> flush
{:ssh_cm, #PID<0.128.0>,
 {:data, 0, 0, "2019年  9月  6日 金曜日 12:36:26 JST\n"}}
{:ssh_cm, #PID<0.128.0>, {:eof, 0}}
{:ssh_cm, #PID<0.128.0>, {:exit_status, 0, 0}}
{:ssh_cm, #PID<0.128.0>, {:closed, 0}}
:ok

参考

www1.erlang.org