<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>
  <header>
    <copyright>
      <year>2012</year>
      <year>2022</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Getting Started</title>
    <prepared></prepared>
    <docno></docno>
    <approved></approved>
    <date></date>
    <rev></rev>
    <file>using_ssh.xml</file>
  </header>

  <section>
    <title>General Information</title>
    <p>The following examples use the utility function
    <seemfa marker="ssh#start/0"> ssh:start/0</seemfa> to start
    all needed applications (<c>crypto</c>, <c>public_key</c>, and <c>ssh</c>).
    All examples are run in an Erlang shell, or in a bash shell, using <em>openssh</em>
    to illustrate how the <c>ssh</c> application can be used. The
    examples are run as the user <c>otptest</c> on a local network where the
    user is authorized to log in over <c>ssh</c> to the host <em>tarlop</em>.
    </p>
    <p>If nothing else is stated, it is presumed that the <c>otptest</c> user
    has an entry in the <em>authorized_keys</em> file of <em>tarlop</em>
    (allowed to log in over <c>ssh</c> without entering a password).
    Also, <em>tarlop</em> is a known host in the <c>known_hosts</c>
    file of the user <c>otptest</c>. This means that host-verification
    can be done without user-interaction.
    </p>
  </section>

  <section>
    <title>Using the Erlang ssh Terminal Client</title>

    <p>The user <c>otptest</c>, which has bash as default shell, uses the
    <c>ssh:shell/1</c> client to connect to the <em>openssh</em> daemon running on a
    host called <em>tarlop</em>:</p>

    <pre>
1> <input>ssh:start().</input>
ok
2> <input>{ok, S} = ssh:shell("tarlop").</input>
otptest@tarlop:> <input>pwd</input>
/home/otptest
otptest@tarlop:> <input>exit</input>
logout
3> </pre>
  </section>

  <section>
    <marker id="Running an Erlang ssh Daemon"></marker>
    <title>Running an Erlang ssh Daemon</title>

    <p>The
    <seetype marker="ssh_file#system_dir_daemon_option"><c>system_dir</c></seetype>
    option must be a directory containing a host key file and it defaults to <c>/etc/ssh</c>.
    For details, see Section Configuration Files in <seeapp marker="SSH_app">ssh(6)</seeapp>.
    </p>

    <note><p>Normally, the <c>/etc/ssh</c> directory is only readable by root.</p>
    </note>

    <p>The option <seetype marker="ssh_file#user_dir_common_option"><c>user_dir</c></seetype>
    defaults to directory <c>users ~/.ssh</c>.</p>

    <p><em>Step 1.</em> To run the example without root privileges,
    generate new keys and host keys:</p>

    <pre>
$bash> <input>ssh-keygen -t rsa -f /tmp/ssh_daemon/ssh_host_rsa_key</input>
[...]
$bash> <input>ssh-keygen -t rsa -f /tmp/otptest_user/.ssh/id_rsa</input>
[...]  </pre>

    <p><em>Step 2.</em> Create the file <c>/tmp/otptest_user/.ssh/authorized_keys</c>
    and add the content of <c>/tmp/otptest_user/.ssh/id_rsa.pub</c>.</p>

    <marker id="start-daemon-step3"></marker>
    <p><em>Step 3.</em> Start the Erlang <c>ssh</c> daemon:</p>

    <pre>
1> <input>ssh:start().</input>
ok
2> <input>{ok, Sshd} = ssh:daemon(8989, [{system_dir, "/tmp/ssh_daemon"},
                                  {user_dir, "/tmp/otptest_user/.ssh"}]).</input>
{ok,&lt;0.54.0>}
3> </pre>

    <p><em>Step 4.</em> Use the <em>openssh</em> client from a shell to connect
    to the Erlang <c>ssh</c> daemon:</p>

    <pre>
$bash> <input>ssh tarlop -p 8989  -i /tmp/otptest_user/.ssh/id_rsa \
                  -o UserKnownHostsFile=/tmp/otptest_user/.ssh/known_hosts</input>
The authenticity of host 'tarlop' can't be established.
RSA key fingerprint is 14:81:80:50:b1:1f:57:dd:93:a8:2d:2f:dd:90:ae:a8.
Are you sure you want to continue connecting (yes/no)? <input>yes</input>
Warning: Permanently added 'tarlop' (RSA) to the list of known hosts.
Eshell V5.10  (abort with ^G)
1>   </pre>

    <p>There are two ways of shutting down an <c>ssh</c> daemon,
    see <em>Step 5a</em> and <em>Step 5b</em>.</p>

    <p><em>Step 5a.</em> Shut down the Erlang <c>ssh</c> daemon so that it
    stops the listener but leaves existing connections, started by the listener,
    operational:</p>

    <pre>
3> <input>ssh:stop_listener(Sshd).</input>
ok
4> </pre>

    <p><em>Step 5b.</em> Shut down the Erlang <c>ssh</c> daemon so that it
    stops the listener and all connections started by the listener:</p>

    <pre>
3> <input>ssh:stop_daemon(Sshd).</input>
ok
4> </pre>
  </section>

  <section>
    <title>One-Time Execution</title>

    <section>
      <marker id="simple-client-example"/>
      <title>Erlang client contacting OS standard ssh server</title>
    <p>In the following example, the Erlang shell is the client process
    that receives the channel replies as Erlang messages.</p>

    <p>Do an one-time execution of a remote OS command ("pwd") over <c>ssh</c> to the
    ssh server of the OS at the host "tarlop":</p>

    <pre>
1> <input>ssh:start().</input>
ok
2> <input>{ok, ConnectionRef} = ssh:connect("tarlop", 22, []).</input>
{ok,&lt;0.57.0>}
3> <input>{ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity).</input>
{ok,0}
4> <input>success = ssh_connection:exec(ConnectionRef, ChannelId, "pwd", infinity).</input>
5> <input>flush().</input> % Get all pending messages. NOTE: ordering may vary!
Shell got {ssh_cm,&lt;0.57.0>,{data,0,0,&lt;&lt;"/home/otptest\n">>}}
Shell got {ssh_cm,&lt;0.57.0>,{eof,0}}
Shell got {ssh_cm,&lt;0.57.0>,{exit_status,0,0}}
Shell got {ssh_cm,&lt;0.57.0>,{closed,0}}
ok
6> <input>ssh:connection_info(ConnectionRef, channels).</input>
{channels,[]}
7></pre>

    <p>See <seeerl marker="ssh_connection#description">ssh_connection</seeerl> and
    <seemfa marker="ssh_connection#exec/4">ssh_connection:exec/4</seemfa>
    for finding documentation of the channel messages.</p>

    <p>To collect the channel messages in a program, use <c>receive...end</c> instead of <c>flush/1</c>:</p>
    <pre>
5> <input>receive</input>
5> <input>    {ssh_cm, ConnectionRef, {data, ChannelId, Type, Result}} when Type == 0 -></input>
5> <input>        {ok,Result}</input>
5> <input>    {ssh_cm, ConnectionRef, {data, ChannelId, Type, Result}} when Type == 1 -></input>
5> <input>        {error,Result}</input>
5> <input>end.</input>
{ok,&lt;&lt;"/home/otptest\n">>}
6></pre>


    <p>Note that only the exec channel is closed after the one-time execution.
    The connection is still up and can handle previously opened channels. It is also
    possible to open a new channel:</p>

    <pre>
% try to open a new channel to check if the ConnectionRef is still open
7> <input>{ok, NewChannelId} = ssh_connection:session_channel(ConnectionRef, infinity).</input>
{ok,1}
8></pre>

    <p>To close the connection, call the function <seemfa marker="ssh#close/1"><c>ssh:close(ConnectionRef)</c></seemfa>.
    As an alternative, set the option
    <seetype marker="ssh#max_idle_time_common_option"><c>{idle_time, 1}</c></seetype>
    when opening the connection. This will cause the connection to be closed automatically when there are
    no channels open for the specified time period, in this case 1 ms.
    </p>
    </section>
    
    <section>
      <title>OS standard client and Erlang daemon (server)</title>
      <p>An Erlang SSH daemon could be called for one-time execution of a "command". The "command" must be
      as if entered into the erlang shell, that is a sequence of Erlang
      <seeguide marker="system/reference_manual:expressions">expressions</seeguide> ended by a period (.).
      Variables bound in that sequence will keep their bindings throughout the expression sequence.
      The bindings are disposed when the result is returned.</p>
      <p>Here is an example of a suitable expression sequence:</p>
      <pre>
A=1, B=2, 3 == (A + B).</pre>
      <p>It evaluates to <c>true</c> if submitted to the Erlang daemon started in
      <seeguide marker="#start-daemon-step3">Step 3</seeguide> above:</p>
      <pre>
$bash> <input>ssh tarlop -p 8989 "A=1, B=2, 3 == (A + B)."</input>
true
$bash></pre>

      <p>The same example but now using the Erlang ssh client to contact the Erlang server:</p>
      <pre>
1> <input>{ok, ConnectionRef} = ssh:connect("tarlop", 8989, []).</input>
{ok,&lt;0.216.0>}
2> <input>{ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity).</input>
{ok,0}
3> <input>success = ssh_connection:exec(ConnectionRef, ChannelId,
                                 "A=1, B=2, 3 == (A + B).",
                                 infinity).</input>
success
4> <input>flush().</input>
Shell got {ssh_cm,&lt;0.216.0>,{data,0,0,&lt;&lt;"true">>}}
Shell got {ssh_cm,&lt;0.216.0>,{exit_status,0,0}}
Shell got {ssh_cm,&lt;0.216.0>,{eof,0}}
Shell got {ssh_cm,&lt;0.216.0>,{closed,0}}
ok
5></pre>
      
      <p>Note that Erlang shell specific functions and control sequences like for example
      <c>h().</c> are not supported.
      </p>
    </section>

    <section>
      <title>I/O from a function called in an Erlang ssh daemon</title>
      
      <p>Output to stdout on the server side is also displayed as well as the resulting term
      from the function call:</p>
      <pre>
$bash> <input>ssh tarlop -p 8989 'io:format("Hello!~n~nHow are ~p?~n",[you]).'</input>
Hello!
 
How are you?
ok
$bash></pre>

      <p>And similar for reading from stdin. As an example we use
      <seemfa marker="stdlib:io#read/1">io:read/1</seemfa> which 
      displays the argument as a prompt on stdout, reads a term from stdin and returns it
      in an ok-tuple:</p>
      <pre>
$bash> <input>ssh tarlop -p 8989 'io:read("write something: ").'</input>
write something: <input>[a,b,c].</input>
{ok,[a,b,c]}
$bash></pre>

      <p>The same example but using the Erlang ssh client:</p>
      <pre>	
Eshell V10.5.2  (abort with ^G)
1> <input>ssh:start().</input>
ok
2> <input>{ok, ConnectionRef} = ssh:connect(loopback, 8989, []).</input>
{ok,&lt;0.92.0>}
3> <input>{ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity).</input>
{ok,0}
4> <input>success = ssh_connection:exec(ConnectionRef, ChannelId,
                                 "io:read(\"write something: \").",
                                 infinity).</input>
success
5> <input>flush().</input>
Shell got {ssh_cm,&lt;0.92.0>,{data,0,0,&lt;&lt;"write something: ">>}}
ok
% All data is sent as binaries with string contents:
6> <input>ok = ssh_connection:send(ConnectionRef, ChannelId, &lt;&lt;"[a,b,c].">>).</input>
ok
7> <input>flush().</input>
ok
%% Nothing is received, because the io:read/1
%% requires the input line to end with a newline.

%% Send a newline (it could have been included in the last send):
8> <input>ssh_connection:send(ConnectionRef, ChannelId, &lt;&lt;"\n">>).</input>
ok
9> <input>flush().</input>
Shell got {ssh_cm,&lt;0.92.0>,{data,0,0,&lt;&lt;"{ok,[a,b,c]}">>}}
Shell got {ssh_cm,&lt;0.92.0>,{exit_status,0,0}}
Shell got {ssh_cm,&lt;0.92.0>,{eof,0}}
Shell got {ssh_cm,&lt;0.92.0>,{closed,0}}
ok
10></pre>
    </section>
    
    <section>
      <title>Configuring the server's (daemon's) command execution</title>
      <p>Every time a daemon <seeguide marker="#running-an-erlang-ssh-daemon">is started</seeguide>, it enables
      one-time execution of commands as described in the
      <seeguide marker="#simple-client-example">previous section</seeguide> unless explicitly disabled.
      </p>

      <p>There is often a need to configure some other exec evaluator to tailor the input language or
      restrict the possible functions to call. There are two ways of doing this which will be shown with examples
      below. See <seemfa marker="ssh#daemon/2">ssh:daemon/2,3</seemfa> and
      <seetype marker="ssh#exec_daemon_option">exec_daemon_option()</seetype>) for details.</p>
      <p>Examples of the two ways to configure the exec evaluator:</p>
      <list type="ordered">
	<item>Disable one-time execution.<br/>
	To modify the daemon start example above to reject one-time execution requests,
	we change <seeguide marker="#start-daemon-step3">Step 3</seeguide> by adding the option
	<c>{exec, disabled}</c>
	to:
	<pre>
1> <input>ssh:start().</input>
ok
2> <input>{ok, Sshd} = ssh:daemon(8989, [{system_dir, "/tmp/ssh_daemon"},
                                  {user_dir, "/tmp/otptest_user/.ssh"},
                                  {exec, disabled}
                                 ]).</input>
{ok,&lt;0.54.0>}
3>	</pre>
	<p>A call to that daemon will return the text "Prohibited." on stderr (depending on the client and OS),
	and the exit status 255:</p>
	<pre>
$bash> <input>ssh tarlop -p 8989 "test."</input>
Prohibited.
$bash> <input>echo $?</input>
255
$bash>	</pre>
	<p>And the Erlang client library also returns the text "Prohibited." on data type 1 instead of the normal 0
	and exit status 255:</p>
	<pre>
2> <input>{ok, ConnectionRef} = ssh:connect(loopback, 8989, []).</input>
{ok,&lt;0.92.0>}
3> <input>{ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity).</input>
{ok,0}
4> <input>success = ssh_connection:exec(ConnectionRef, ChannelId, "test."</input>
success
5> <input>flush().</input>
Shell got {ssh_cm,&lt;0.106.0>,{data,0,1,&lt;&lt;"Prohibited.">>}}
Shell got {ssh_cm,&lt;0.106.0>,{exit_status,0,255}}
Shell got {ssh_cm,&lt;0.106.0>,{eof,0}}
Shell got {ssh_cm,&lt;0.106.0>,{closed,0}}
ok
6></pre>
	</item>
	
	<item>Install an alternative evaluator.<br/>
	Start the damon with a reference to a <c>fun()</c> that handles the evaluation:
	<pre>
1> <input>ssh:start().</input>
ok
2> <input>MyEvaluator = fun("1") -> {ok, some_value};
                    ("2") -> {ok, some_other_value};
                    ("3") -> {ok, V} = io:read("input erlang term>> "),
                             {ok, V};
                    (Err) -> {error,{bad_input,Err}}
                 end.</input>
3> <input>{ok, Sshd} = ssh:daemon(1234, [{system_dir, "/tmp/ssh_daemon"},
                                  {user_dir, "/tmp/otptest_user/.ssh"},
                                  {exec, {direct,MyEvaluator}}
                                 ]).</input>
{ok,&lt;0.275.0>}
4></pre>
	and call it:
	<pre>
$bash> <input>ssh localhost -p 1234 1</input>
some_value
$bash> <input>ssh localhost -p 1234 2</input>
some_other_value
# I/O works:
$bash> <input>ssh localhost -p 1234 3</input>
input erlang term>> <input>abc.</input>
abc
# Check that Erlang evaluation is disabled:
$bash> <input>ssh localhost -p 1234 1+ 2.</input>
**Error** {bad_input,"1+ 2."}
$bash> 	</pre>
	Note that spaces are preserved and that no point (.) is needed at the end - that was required
	by the default evaluator.
	<p>The error return in the Erlang client (The text as data type 1 and exit_status 255):</p>
	<pre>
2> <input>{ok, ConnectionRef} = ssh:connect(loopback, 1234, []).</input>
{ok,&lt;0.92.0>}
3> <input>{ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity).</input>
{ok,0}
4> <input>success = ssh_connection:exec(ConnectionRef, ChannelId, "1+ 2.").</input>
success
5> <input>flush().</input>
Shell got {ssh_cm,&lt;0.106.0>,{data,0,1,&lt;&lt;"**Error** {bad_input,\"1+ 2.\"}">>}}
Shell got {ssh_cm,&lt;0.106.0>,{exit_status,0,255}}
Shell got {ssh_cm,&lt;0.106.0>,{eof,0}}
Shell got {ssh_cm,&lt;0.106.0>,{closed,0}}
ok
6></pre>
	<p>The <c>fun()</c> in the exec option could take up to three arguments
	(<c>Cmd</c>, <c>User</c> and <c>ClientAddress</c>). See
	the <seetype marker="ssh#exec_daemon_option">exec_daemon_option()</seetype> for the details.</p>
	</item>
      </list>


      <note><p>An old, discouraged and undocumented way of installing an alternative evaluator exists.</p>
      <p>It still works, but lacks
      for example I/O possibility. It is because of that compatibility we need
      the <c>{direct,...}</c>	construction.
      </p>
      </note>
    </section>

  </section>

  <section>
    <title>SFTP Server</title>

    <p>Start the Erlang <c>ssh</c> daemon with the SFTP subsystem:</p>

    <pre>
1> <input>ssh:start().</input>
ok
2> <input>ssh:daemon(8989, [{system_dir, "/tmp/ssh_daemon"},
                     {user_dir, "/tmp/otptest_user/.ssh"},
                     {subsystems, [ssh_sftpd:subsystem_spec(
                                            [{cwd, "/tmp/sftp/example"}])
                                  ]}]).</input>
{ok,&lt;0.54.0>}
3> </pre>

    <p>Run the OpenSSH SFTP client:</p>

    <pre>
$bash> <input>sftp -oPort=8989 -o IdentityFile=/tmp/otptest_user/.ssh/id_rsa \
            -o UserKnownHostsFile=/tmp/otptest_user/.ssh/known_hosts tarlop</input>
Connecting to tarlop...
sftp> <input>pwd</input>
Remote working directory: /tmp/sftp/example
sftp> </pre>
  </section>

  <section>
    <title>SFTP Client</title>

    <p>Fetch a file with the Erlang SFTP client:</p>

    <pre>
1> <input>ssh:start().</input>
ok
2> <input>{ok, ChannelPid, Connection} = ssh_sftp:start_channel("tarlop", []).</input>
{ok,&lt;0.57.0>,&lt;0.51.0>}
3> <input>ssh_sftp:read_file(ChannelPid, "/home/otptest/test.txt").</input>
{ok,&lt;&lt;"This is a test file\n">>} </pre>
  </section>

  <section>
    <title>SFTP Client with TAR Compression</title>
    <section>
      <title>Basic example</title>
    <p>This is an example of writing and then reading a tar file:</p>
    <code type="erl">
{ok,HandleWrite} = ssh_sftp:open_tar(ChannelPid, ?tar_file_name, [write]),
ok = erl_tar:add(HandleWrite, .... ),
ok = erl_tar:add(HandleWrite, .... ),
...
ok = erl_tar:add(HandleWrite, .... ),
ok = erl_tar:close(HandleWrite),

%% And for reading
{ok,HandleRead} = ssh_sftp:open_tar(ChannelPid, ?tar_file_name, [read]),
{ok,NameValueList} = erl_tar:extract(HandleRead,[memory]),
ok = erl_tar:close(HandleRead),
    </code>
  </section>

  <section>
    <title>Example with encryption</title>
    <p>The previous <seeguide marker="using_ssh#basic-example">Basic example</seeguide>
    can be extended with encryption and decryption as follows:</p>
    <code type="erl">
%% First three parameters depending on which crypto type we select:
Key = &lt;&lt;"This is a 256 bit key. abcdefghi">>,
Ivec0 = crypto:strong_rand_bytes(16),
DataSize = 1024,  % DataSize rem 16 = 0 for aes_cbc

%% Initialization of the CryptoState, in this case it is the Ivector.
InitFun = fun() -> {ok, Ivec0, DataSize} end,

%% How to encrypt:
EncryptFun =
    fun(PlainBin,Ivec) ->
        EncryptedBin = crypto:block_encrypt(aes_cbc256, Key, Ivec, PlainBin),
        {ok, EncryptedBin, crypto:next_iv(aes_cbc,EncryptedBin)}
    end,

%% What to do with the very last block:
CloseFun =
    fun(PlainBin, Ivec) ->
        EncryptedBin = crypto:block_encrypt(aes_cbc256, Key, Ivec,
                                            pad(16,PlainBin) %% Last chunk
                                           ),
       {ok, EncryptedBin}
    end,

Cw = {InitFun,EncryptFun,CloseFun},
{ok,HandleWrite} = ssh_sftp:open_tar(ChannelPid, ?tar_file_name, [write,{crypto,Cw}]),
ok = erl_tar:add(HandleWrite, .... ),
ok = erl_tar:add(HandleWrite, .... ),
...
ok = erl_tar:add(HandleWrite, .... ),
ok = erl_tar:close(HandleWrite),

%% And for decryption (in this crypto example we could use the same InitFun
%% as for encryption):
DecryptFun =
    fun(EncryptedBin,Ivec) ->
        PlainBin = crypto:block_decrypt(aes_cbc256, Key, Ivec, EncryptedBin),
       {ok, PlainBin, crypto:next_iv(aes_cbc,EncryptedBin)}
    end,

Cr = {InitFun,DecryptFun},
{ok,HandleRead} = ssh_sftp:open_tar(ChannelPid, ?tar_file_name, [read,{crypto,Cw}]),
{ok,NameValueList} = erl_tar:extract(HandleRead,[memory]),
ok = erl_tar:close(HandleRead),
    </code>
  </section>
  </section>

  <section>
    <marker id="usersguide_creating_a_subsystem"/>
    <title>Creating a Subsystem</title>

    <p>A small <c>ssh</c> subsystem that echoes N bytes can be implemented as shown
    in the following example:</p>

    <code type="erl" >
-module(ssh_echo_server).
-behaviour(ssh_server_channel). % replaces ssh_daemon_channel
-record(state, {
	  n,
	  id,
	  cm
	 }).
-export([init/1, handle_msg/2, handle_ssh_msg/2, terminate/2]).

init([N]) ->
    {ok, #state{n = N}}.

handle_msg({ssh_channel_up, ChannelId, ConnectionManager}, State) ->
    {ok, State#state{id = ChannelId,
		     cm = ConnectionManager}}.

handle_ssh_msg({ssh_cm, CM, {data, ChannelId, 0, Data}}, #state{n = N} = State) ->
    M = N - size(Data),
    case M > 0 of
	true ->
	   ssh_connection:send(CM, ChannelId, Data),
	   {ok, State#state{n = M}};
	false ->
	   &lt;&lt;SendData:N/binary, _/binary>> = Data,
           ssh_connection:send(CM, ChannelId, SendData),
           ssh_connection:send_eof(CM, ChannelId),
	   {stop, ChannelId, State}
    end;
handle_ssh_msg({ssh_cm, _ConnectionManager,
		{data, _ChannelId, 1, Data}}, State) ->
    error_logger:format(standard_error, " ~p~n", [binary_to_list(Data)]),
    {ok, State};

handle_ssh_msg({ssh_cm, _ConnectionManager, {eof, _ChannelId}}, State) ->
    {ok, State};

handle_ssh_msg({ssh_cm, _, {signal, _, _}}, State) ->
    %% Ignore signals according to RFC 4254 section 6.9.
    {ok, State};

handle_ssh_msg({ssh_cm, _, {exit_signal, ChannelId, _, _Error, _}},
	       State) ->
    {stop, ChannelId,  State};

handle_ssh_msg({ssh_cm, _, {exit_status, ChannelId, _Status}}, State) ->
    {stop, ChannelId, State}.

terminate(_Reason, _State) ->
    ok.
 </code>

 <p>The subsystem can be run on the host <em>tarlop</em> with the generated keys,
 as described in Section <seeguide marker="#Running an Erlang ssh Daemon">
 Running an Erlang ssh Daemon</seeguide>:</p>

 <pre>
1> <input>ssh:start().</input>
ok
2> <input>ssh:daemon(8989, [{system_dir, "/tmp/ssh_daemon"},
                     {user_dir, "/tmp/otptest_user/.ssh"}
                     {subsystems, [{"echo_n", {ssh_echo_server, [10]}}]}]).</input>
{ok,&lt;0.54.0>}
3> </pre>

 <pre>
1> <input>ssh:start().</input>
ok
2> <input>{ok, ConnectionRef} = ssh:connect("tarlop", 8989,
                                    [{user_dir, "/tmp/otptest_user/.ssh"}]).</input>
 {ok,&lt;0.57.0>}
3> <input>{ok, ChannelId} = ssh_connection:session_channel(ConnectionRef, infinity).</input>
4> <input>success = ssh_connection:subsystem(ConnectionRef, ChannelId, "echo_n", infinity).</input>
5> <input>ok = ssh_connection:send(ConnectionRef, ChannelId, "0123456789", infinity).</input>
6> <input>flush().</input>
{ssh_msg, &lt;0.57.0>, {data, 0, 1, "0123456789"}}
{ssh_msg, &lt;0.57.0>, {eof, 0}}
{ssh_msg, &lt;0.57.0>, {closed, 0}}
7> <input>{error, closed} = ssh_connection:send(ConnectionRef, ChannelId, "10", infinity).</input> </pre>
 
<p>See also <seeerl marker="ssh_client_channel">ssh_client_channel(3)</seeerl> (replaces ssh_channel(3)).</p>

</section>

</chapter>
