ssh

v5.5.2

ssh

Main API of the ssh application

This is the interface module for the SSH application. The Secure Shell (SSH) Protocol is a protocol for secure remote login and other secure network services over an insecure network. See ssh for details of supported RFCs, versions, algorithms and unicode handling.

With the SSH application it is possible to start clients and to start daemons (servers).

Clients are started with connect/2, connect/3 or connect/4. They open an encrypted connection on top of TCP/IP. In that encrypted connection one or more channels could be opened with ssh_connection:session_channel/2,4.

Each channel is an isolated "pipe" between a client-side process and a server-side process. Those process pairs could handle for example file transfers (sftp) or remote command execution (shell, exec and/or cli). If a custom shell is implemented, the user of the client could execute the special commands remotely. Note that the user is not necessarily a human but probably a system interfacing the SSH application.

A server-side subssystem (channel) server is requested by the client with ssh_connection:subsystem/4.

A server (daemon) is started with daemon/1, daemon/2 or daemon/3. Possible channel handlers (subsystems) are declared with the subsystem option when the daemon is started.

To just run a shell on a remote machine, there are functions that bundles the needed three steps needed into one: shell/1,2,3. Similarly, to just open an sftp (file transfer) connection to a remote machine, the simplest way is to use ssh_sftp:start_channel/1,2,3.

To write your own client channel handler, use the behaviour ssh_client_channel. For server channel handlers use ssh_server_channel behaviour (replaces ssh_daemon_channel).

Both clients and daemons accept options that control the exact behaviour. Some options are common to both. The three sets are called Client Options, Daemon Options and Common Options.

The descriptions of the options uses the Erlang Type Language with explaining text.

Note

See also SSH Application Reference and Examples section.

Keys and files

A number of objects must be present for the SSH application to work. Those objects are per default stored in files. The default names, paths and file formats are the same as for OpenSSH. Keys could be generated with the ssh-keygen program from OpenSSH. See the User's Guide.

The paths could easily be changed by options: user_dir and system_dir.

A completely different storage could be interfaced by writing callback modules using the behaviours ssh_client_key_api and/or ssh_server_key_api. A callback module is installed with the option key_cb to the client and/or the daemon.

Daemons

The keys are by default stored in files:

Mandatory: one or more Host key(s), both private and public. Default is to store them in the directory /etc/ssh in the files

ssh_host_dsa_key and ssh_host_dsa_key.pub

ssh_host_rsa_key and ssh_host_rsa_key.pub

ssh_host_ecdsa_key and ssh_host_ecdsa_key.pub

The host keys directory could be changed with the option system_dir.

Optional: one or more User's public key in case of publickey authorization. Default is to store them concatenated in the file .ssh/authorized_keys in the user's home directory.

The user keys directory could be changed with the option user_dir.

Clients

The keys and some other data are by default stored in files in the directory .ssh in the user's home directory.

The directory could be changed with the option user_dir.

Optional: a list of Host public key(s) for previously connected hosts. This list is handled by the SSH application without any need of user assistance. The default is to store them in the file known_hosts.

The host_accepting_client_options/0 are associated with this list of keys.

Optional: one or more User's private key(s) in case of publickey authorization. The default files are

id_dsa and id_dsa.pub

id_rsa and id_rsa.pub

id_ecdsa and id_ecdsa.pub

Summary

Types: Client Options

accept_callback()

accept_hosts()

authentication_client_options()

client_option()

Options for clients. The individual options are further explained below or by following the hyperlinks.

client_options()

connect_timeout_client_option()

Sets a timeout on the transport layer connect time. For gen_tcp the time is in milli-seconds and the default value is infinity.

diffie_hellman_group_exchange_client_option()

Sets the three diffie-hellman-group-exchange parameters that guides the connected server in choosing a group. See RFC 4419 for the details. The default value is {1024, 6144, 8192}.

fingerprint()

fp_digest_alg()

host_accepting_client_options()

recv_ext_info_client_option()

Make the client tell the server that the client accepts extension negotiation, that is, include ext-info-c in the kexinit message sent. See RFC 8308 for details and ssh for a list of currently implemented extensions.

Types: Common Options

alg_entry()

algs_list()

alive_common_option()

This option is used to configure the alive messages. Alive messages are sent through the encrypted channel and are typically used to detect that a connection became unresponsive.

auth_methods_common_option()

Comma-separated string that determines which authentication methods that the client shall support and in which order they are tried. Defaults to "publickey,keyboard-interactive,password"

cipher_alg()

common_option()

The options above can be used both in clients and in daemons (servers). They are further explained below.

common_options()

compression_alg()

disabled_cipher_alg()

disabled_mac_alg()

disconnectfun_common_option()

Provides a fun to implement your own logging or other handling at disconnects.

double_algs(AlgType)

List of algorithms to use in the algorithm negotiation. The default algs_list/0 can be obtained from default_algorithms/0.

fd_common_option()

Allows an existing file-descriptor to be used (passed on to the transport protocol).

id_string_common_option()

The string the daemon will present to a connecting peer initially. The default value is "Erlang/VSN" where VSN is the ssh application version number.

inet_common_option()

IP version to use when the host address is specified as any.

kex_alg()

key_cb_common_option()

Module implementing the behaviour ssh_client_key_api and/or ssh_server_key_api. Can be used to customize the handling of public keys. If callback options are provided along with the module name, they are made available to the callback module via the options passed to it under the key 'key_cb_private'.

limit_bytes()

limit_time()

Sets the limit when rekeying is to be initiated. Both the max time and max amount of data could be configured

mac_alg()

max_idle_time_common_option()

Sets a time-out on a connection when no channels are open. Defaults to infinity. The unit is milliseconds.

max_log_item_len_common_option()

Sets a limit for the size of a logged item excluding a header. The unit is bytes and the value defaults to 500.

modify_algorithms_common_option()

modify_algs_list()

Modifies the list of algorithms to use in the algorithm negotiation. The modifications are applied after the option preferred_algorithms (if existing) is applied.

pref_public_key_algs_common_option()

List of user (client) public key algorithms to try to use.

preferred_algorithms_common_option()

profile_common_option()

Used together with ip-address and port to uniquely identify a ssh daemon. This can be useful in a virtualized environment, where there can be more that one server that has the same ip-address and port. If this property is not explicitly set, it is assumed that the the ip-address and port uniquely identifies the SSH daemon.

pubkey_alg()

rekey_limit_common_option()

ssh_msg_debug_fun_common_option()

Provide a fun to implement your own logging of the SSH message SSH_MSG_DEBUG. The last three parameters are from the message, see RFC 4253, section 11.3. The connection_ref/0 is the reference to the connection on which the message arrived. The return value from the fun is not checked.

unexpectedfun_common_option()

Provides a fun to implement your own logging or other action when an unexpected message arrives. If the fun returns report the usual info report is issued but if skip is returned no report is generated.

Types: Daemon Options

authentication_daemon_options()

callbacks_daemon_options()

daemon_option()

Options for daemons. The individual options are further explained below or by following the hyperlinks.

daemon_options()

deprecated_exec_opt()

Old-style exec specification that are kept for compatibility, but should not be used in new programs

diffie_hellman_group_exchange_daemon_option()

exec_daemon_option()

exec_fun()

The default is disabled.

'exec_fun/1'()

'exec_fun/2'()

'exec_fun/3'()

exec_result()

This option changes how the daemon executes exec-requests from clients. The term in the return value is formatted to a string if it is a non-string type. No trailing newline is added in the ok-case.

exec_spec()

explicit_group()

explicit_group_file()

hardening_daemon_options()

For more information about hardening, see the Hardening section in the User's Guide chapter.

hello_timeout_daemon_option()

Maximum time in milliseconds for the first part of the ssh session setup, the hello message exchange. Defaults to 30000 ms (30 seconds). If the client fails to send the first message within this time, the connection is closed.

kb_int_fun_3()

kb_int_fun_4()

kb_int_tuple()

max_initial_idle_time_daemon_option()

Maximum time in milliseconds for the first channel start after completion of the authentication negotiation. Defaults to infinity.

negotiation_timeout_daemon_option()

Maximum time in milliseconds for the authentication negotiation. Defaults to 120000 ms (2 minutes). If the client fails to log in within this time, the connection is closed.

prompt_texts()

pwdfun_2()

Equivalent to pwdfun_4/0.

pwdfun_4()

send_ext_info_daemon_option()

Make the server (daemon) tell the client that the server accepts extension negotiation, that is, include ext-info-s in the kexinit message sent. See RFC 8308 for details and ssh for a list of currently implemented extensions.

shell_daemon_option()

Equivalent to 'shell_fun/2'/0.

shell_fun()

The default is disabled.

'shell_fun/1'()

Equivalent to 'shell_fun/2'/0.

'shell_fun/2'()

Defines the read-eval-print loop used in a daemon when a shell is requested by the client.

shell_spec()

ssh_cli_daemon_option()

Provides your own CLI implementation in a daemon.

ssh_moduli_file()

subsystem_daemon_option()

subsystem_spec()

Defines a subsystem in the daemon.

subsystem_specs()

tcpip_tunnel_in_daemon_option()

Enables (true) or disables (false) the possibility to tunnel a TCP/IP connection in to a server. Disabled per default.

tcpip_tunnel_out_daemon_option()

Enables (true) or disables (false) the possibility to tunnel a TCP/IP connection out of a server. Disabled per default.

Types: Deprecated

ssh_channel_id()

ssh_connection_ref()

ssh_daemon_ref()

Types: Legacy Algorithms

legacy_cipher_alg()

legacy_compression_alg() deprecated

Deprecated: the use of zlib compression in SSH will be removed in OTP 30.0. Use none or zlib@openssh.com instead.

legacy_kex_alg()

legacy_mac_alg()

legacy_pubkey_alg()

Types

channel_id()

Opaque data type representing a channel inside a connection.

conn_info_algs()

conn_info_channels()

connection_info_tuple()

Return values from the connection_info/1 and connection_info/2 functions.

connection_ref()

Opaque data type representing a connection between a client and a server (daemon).

daemon_info_tuple()

Return values from the daemon_info/1 and daemon_info/2 functions.

daemon_ref()

Opaque data type representing a daemon.

experimental_client_options()

Experimental options that should not to be used in products.

experimental_common_options()

Experimental options that should not to be used in products.

experimental_daemon_options()

Experimental options that should not to be used in products.

host()

ip_port()

mod_args()

mod_fun_args()

open_socket()

The socket is supposed to be result of a gen_tcp:connect or a gen_tcp:accept. The socket must be in passive mode (that is, opened with the option {active,false}).

protocol_version()

role()

software_version()

version()

Functions

close(ConnectionRef)

Closes an SSH connection.

connect(OpenTcpSocket, Options)

Equivalent to connect/4.

connect/3

Equivalent to connect/4.

connect(Host, Port, Options, NegotiationTimeout)

Connects to an SSH server at the Host on Port.

connection_info(ConnectionRef)

Equivalent to connection_info/2.

connection_info(ConnectionRef, Key)

Returns information about a connection intended for e.g debugging or logging.

daemon(Port)

Equivalent to daemon/3.

daemon/2

Equivalent to daemon/3.

daemon(HostAddress, Port, Options)

Starts a server listening for SSH connections on the given port. If the Port is 0, a random free port is selected. See daemon_info/1 about how to find the selected port number.

daemon_info(DaemonRef)

Equivalent to daemon_info/2.

daemon_info/2

Returns information about a daemon intended for e.g debugging or logging.

daemon_replace_options(DaemonRef, NewUserOptions)

Replaces the options in a running daemon with the options in NewUserOptions. Only connections established after this call are affected, already established connections are not.

default_algorithms()

Returns a key-value list, where the keys are the different types of algorithms and the values are the algorithms themselves.

get_sock_opts(ConnectionRef, SocketGetOptions)

Get tcp socket option values of the tcp-socket below an ssh connection.

hostkey_fingerprint(Key)

Equivalent to hostkey_fingerprint/2.

hostkey_fingerprint(TypeOrTypes, Key)

hostkey_fingerprint([DigestType], HostKey) -> [string()]hostkey_fingerprint(DigestType, HostKey) -> string()

set_sock_opts(ConnectionRef, SocketOptions)

Sets tcp socket options on the tcp-socket below an ssh connection.

shell/1

Equivalent to shell/3.

shell(Dest, Options)

Equivalent to shell/3.

shell(Host, Port, Options)

Connects to an SSH server at Host and Port (defaults to 22) and starts an interactive shell on that remote host.

start()

Equivalent to start/1.

start(Type)

Utility function that starts the applications crypto, public_key, and ssh. Default type is temporary. For more information, see the application manual page in Kernel.

stop()

Stops the ssh application. For more information, see the application manual page in Kernel.

stop_daemon(DaemonRef)

Equivalent to stop_daemon/3.

stop_daemon(Address, Port)

Equivalent to stop_daemon/3.

stop_daemon(Address, Port, Profile)

Stops the listener and all connections started by the listener.

stop_listener(SysSup)

Equivalent to stop_listener/3.

stop_listener(Address, Port)

Equivalent to stop_listener/3.

stop_listener(Address, Port, Profile)

Stops the listener, but leaves existing connections started by the listener operational.

tcpip_tunnel_from_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort)

Equivalent to tcpip_tunnel_from_server/6.

tcpip_tunnel_from_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort, Timeout)

Asks the remote server of ConnectionRef to listen to ListenHost:ListenPort. When someone connects that address, the connection is forwarded in an encrypted channel from the server to the client. The client (that is, at the node that calls this function) then connects to ConnectToHost:ConnectToPort.

tcpip_tunnel_to_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort)

Equivalent to tcpip_tunnel_to_server/6.

tcpip_tunnel_to_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort, Timeout)

Tells the local client to listen to ListenHost:ListenPort. When someone connects to that address, the connection is forwarded in an encrypted channel to the peer server of ConnectionRef. That server then connects to ConnectToHost:ConnectToPort.

Types: Client Options

accept_callback()

-type accept_callback() ::
          fun((PeerName :: string(), fingerprint()) -> boolean()) |
          fun((PeerName :: string(), Port :: inet:port_number(), fingerprint()) -> boolean()).

accept_hosts()

-type accept_hosts() ::
          boolean() | accept_callback() | {HashAlgoSpec :: fp_digest_alg(), accept_callback()}.

authentication_client_options()

-type authentication_client_options() :: {user, string()} | {password, string()}.

user - Provides the username. If this option is not given, ssh reads from the environment (LOGNAME or USER on UNIX, USERNAME on Windows).

password - Provides a password for password authentication. If this option is not given, the user is asked for a password, if the password authentication method is attempted.

client_option()

-type client_option() ::
          ssh_file:pubkey_passphrase_client_options() |
          host_accepting_client_options() |
          authentication_client_options() |
          diffie_hellman_group_exchange_client_option() |
          connect_timeout_client_option() |
          recv_ext_info_client_option() |
          gen_tcp:connect_option() |
          common_option() |
          experimental_client_options().

Options for clients. The individual options are further explained below or by following the hyperlinks.

Note that not every gen_tcp:connect_option/0 is accepted. See set_sock_opts/2 for a list of prohibited options.

Also note that setting a gen_tcp:connect_option/0 could change the socket in a way that impacts the ssh client's behaviour negatively. You use it on your own risk.

client_options()

-type client_options() :: [client_option()].

connect_timeout_client_option()

-type connect_timeout_client_option() :: {connect_timeout, timeout()}.

Sets a timeout on the transport layer connect time. For gen_tcp the time is in milli-seconds and the default value is infinity.

See the parameter Timeout in connect/4 for a timeout of the negotiation phase.

diffie_hellman_group_exchange_client_option()

-type diffie_hellman_group_exchange_client_option() ::
          {dh_gex_limits, {Min :: pos_integer(), I :: pos_integer(), Max :: pos_integer()}}.

Sets the three diffie-hellman-group-exchange parameters that guides the connected server in choosing a group. See RFC 4419 for the details. The default value is {1024, 6144, 8192}.

fingerprint()

-type fingerprint() :: string() | [string()].

fp_digest_alg()

-type fp_digest_alg() :: md5 | crypto:sha1() | crypto:sha2().

host_accepting_client_options()

-type host_accepting_client_options() ::
          {silently_accept_hosts, accept_hosts()} |
          {user_interaction, boolean()} |
          {save_accepted_host, boolean()} |
          {quiet_mode, boolean()}.

silently_accept_hosts - This option guides the connect function on how to act when the connected server presents a Host Key that the client has not seen before. The default is to ask the user with a question on stdio of whether to accept or reject the new Host Key. See the option user_dir for specifying the path to the file known_hosts where previously accepted Host Keys are recorded. See also the option key_cb for the general way to handle keys.

The option can be given in three different forms as seen above:

The value is a boolean/0. The value true will make the client accept any unknown Host Key without any user interaction. The value false preserves the default behaviour of asking the user on stdio.

An accept_callback/0 will be called and the boolean return value true will make the client accept the Host Key. A return value of false will make the client to reject the Host Key and as a result the connection will be closed. The arguments to the fun are:

PeerName - a string with the name or address of the remote host.

FingerPrint - the fingerprint of the Host Key as hostkey_fingerprint/1 calculates it.

A tuple {HashAlgoSpec, accept_callback}. The HashAlgoSpec specifies which hash algorithm shall be used to calculate the fingerprint used in the call of the accept_callback/0. The HashALgoSpec is either an atom or a list of atoms as the first argument in hostkey_fingerprint/2. If it is a list of hash algorithm names, the FingerPrint argument in the accept_callback/0 will be a list of fingerprints in the same order as the corresponding name in the HashAlgoSpec list.

user_interaction - If false, disables the client to connect to the server if any user interaction is needed, such as accepting the server to be added to the known_hosts file, or supplying a password.

Even if user interaction is allowed it can be suppressed by other options, such as silently_accept_hosts and password. However, those options are not always desirable to use from a security point of view.

Defaults to true.

save_accepted_host - If true, the client saves an accepted host key to avoid the accept question the next time the same host is connected. If the option key_cb is not present, the key is saved in the file "known_hosts". See option user_dir for the location of that file.

If false, the key is not saved and the key will still be unknown at the next access of the same host.

Defaults to true

quiet_mode - If true, the client does not print anything on authorization.

Defaults to false

recv_ext_info_client_option()

-type recv_ext_info_client_option() :: {recv_ext_info, boolean()}.

Make the client tell the server that the client accepts extension negotiation, that is, include ext-info-c in the kexinit message sent. See RFC 8308 for details and ssh for a list of currently implemented extensions.

Default value is true which is compatible with other implementations not supporting ext-info.

Types: Common Options

alg_entry()

-type alg_entry() ::
          {kex, [kex_alg()]} |
          {public_key, [pubkey_alg()]} |
          {cipher, double_algs(cipher_alg())} |
          {mac, double_algs(mac_alg())} |
          {compression, double_algs(compression_alg())}.

algs_list()

-type algs_list() :: [alg_entry()].

alive_common_option()

-type alive_common_option() ::
          {alive, #{count_max := CountMax :: pos_integer(), interval := Interval :: timeout()}}.

This option is used to configure the alive messages. Alive messages are sent through the encrypted channel and are typically used to detect that a connection became unresponsive.

count_max sets the maximum number of alive messages which may be sent without receiving any messages back from the peer. If this threshold is reached the connection will be terminated. interval sets a timeout interval, in milliseconds, after which, if no data has been received from the peer, a message to request a response from the peer is sent.

The default is #{count_max => 3, interval => infinity}, which means that alive messages will not be sent to the peer, since the interval is set to infinity.

No alive messages are sent during renegotiation, however, a timeout derived from the alive parameters is set to ensure that unresponsive connections are terminated.

auth_methods_common_option()

-type auth_methods_common_option() :: {auth_methods, string()}.

Comma-separated string that determines which authentication methods that the client shall support and in which order they are tried. Defaults to "publickey,keyboard-interactive,password"

Note that the client is free to use any order and to exclude methods.

cipher_alg()

-type cipher_alg() ::
          'aes128-ctr' | 'aes128-gcm@openssh.com' | 'aes192-ctr' | 'aes256-ctr' |
          'aes256-gcm@openssh.com' | 'chacha20-poly1305@openssh.com' |
          disabled_cipher_alg() |
          legacy_cipher_alg().

common_option()

-type common_option() ::
          ssh_file:user_dir_common_option() |
          profile_common_option() |
          max_idle_time_common_option() |
          max_log_item_len_common_option() |
          key_cb_common_option() |
          disconnectfun_common_option() |
          unexpectedfun_common_option() |
          ssh_msg_debug_fun_common_option() |
          rekey_limit_common_option() |
          id_string_common_option() |
          pref_public_key_algs_common_option() |
          preferred_algorithms_common_option() |
          modify_algorithms_common_option() |
          auth_methods_common_option() |
          inet_common_option() |
          fd_common_option() |
          alive_common_option().

The options above can be used both in clients and in daemons (servers). They are further explained below.

common_options()

-type common_options() :: [common_option()].

compression_alg()

-type compression_alg() :: none | 'zlib@openssh.com' | legacy_compression_alg().

disabled_cipher_alg()

-type disabled_cipher_alg() :: 'AEAD_AES_128_GCM' | 'AEAD_AES_256_GCM'.

disabled_mac_alg()

-type disabled_mac_alg() :: 'AEAD_AES_128_GCM' | 'AEAD_AES_256_GCM'.

disconnectfun_common_option()

-type disconnectfun_common_option() :: {disconnectfun, fun((Reason :: term()) -> void | any())}.

Provides a fun to implement your own logging or other handling at disconnects.

double_algs(AlgType)

-type double_algs(AlgType) :: [{client2server, [AlgType]} | {server2client, [AlgType]}] | [AlgType].

List of algorithms to use in the algorithm negotiation. The default algs_list/0 can be obtained from default_algorithms/0.

If an alg_entry() is missing in the algs_list(), the default value is used for that entry.

Here is an example of this option:

	  {preferred_algorithms,
	  [{public_key,['ssh-rsa','ssh-dss']},
	  {cipher,[{client2server,['aes128-ctr']},
          {server2client,['aes128-cbc','3des-cbc']}]},
	  {mac,['hmac-sha2-256','hmac-sha1']},
	  {compression,[none,zlib]}
	  ]
	  }

The example specifies different algorithms in the two directions (client2server and server2client), for cipher but specifies the same algorithms for mac and compression in both directions. The kex (key exchange) is implicit but public_key is set explicitly.

For background and more examples see the User's Guide.

If an algorithm name occurs more than once in a list, the behaviour is undefined. The tags in the property lists are also assumed to occur at most one time.

Warning

Changing the values can make a connection less secure. Do not change unless you know exactly what you are doing. If you do not understand the values then you are not supposed to change them.

fd_common_option()

-type fd_common_option() :: {fd, gen_tcp:socket()}.

Allows an existing file-descriptor to be used (passed on to the transport protocol).

id_string_common_option()

-type id_string_common_option() ::
          {id_string, string() | random | {random, Nmin :: pos_integer(), Nmax :: pos_integer()}}.

The string the daemon will present to a connecting peer initially. The default value is "Erlang/VSN" where VSN is the ssh application version number.

The value random will cause a random string to be created at each connection attempt. This is to make it a bit more difficult for a malicious peer to find the ssh software brand and version.

The value {random, Nmin, Nmax} will make a random string with at least Nmin characters and at most Nmax characters.

inet_common_option()

-type inet_common_option() :: {inet, inet | inet6}.

IP version to use when the host address is specified as any.

kex_alg()

-type kex_alg() ::
          'diffie-hellman-group-exchange-sha256' | 'diffie-hellman-group14-sha256' |
          'diffie-hellman-group16-sha512' | 'diffie-hellman-group18-sha512' | 'curve25519-sha256' |
          'curve25519-sha256@libssh.org' | 'curve448-sha512' | 'ecdh-sha2-nistp256' |
          'ecdh-sha2-nistp384' | 'ecdh-sha2-nistp521' | 'mlkem768x25519-sha256' |
          legacy_kex_alg().

key_cb_common_option()

-type key_cb_common_option() :: {key_cb, Module :: atom() | {Module :: atom(), Opts :: [term()]}}.

Module implementing the behaviour ssh_client_key_api and/or ssh_server_key_api. Can be used to customize the handling of public keys. If callback options are provided along with the module name, they are made available to the callback module via the options passed to it under the key 'key_cb_private'.

The Opts defaults to [] when only the Module is specified.

The default value of this option is {ssh_file, []}. See also the manpage of ssh_file.

A call to the call-back function F will be

	  Module:F(..., [{key_cb_private,Opts}|UserOptions])

where ... are arguments to F as in ssh_client_key_api and/or ssh_server_key_api. The UserOptions are the options given to ssh:connect, ssh:shell or ssh:daemon.

limit_bytes()

-type limit_bytes() :: non_neg_integer() | infinity.

limit_time()

-type limit_time() :: pos_integer() | infinity.

Sets the limit when rekeying is to be initiated. Both the max time and max amount of data could be configured:

{Minutes, Bytes} initiate rekeying when any of the limits are reached.

Bytes initiate rekeying when Bytes number of bytes are transferred, or at latest after one hour.

When a rekeying is done, both the timer and the byte counter are restarted. Defaults to one hour and one GByte.

If Minutes is set to infinity, no rekeying will ever occur due to that max time has passed. Setting Bytes to infinity will inhibit rekeying after a certain amount of data has been transferred. If the option value is set to {infinity, infinity}, no rekeying will be initiated. Note that rekeying initiated by the peer will still be performed.

mac_alg()

-type mac_alg() ::
          'hmac-sha1' | 'hmac-sha1-etm@openssh.com' | 'hmac-sha2-256' | 'hmac-sha2-512' |
          'hmac-sha2-256-etm@openssh.com' | 'hmac-sha2-512-etm@openssh.com' |
          disabled_mac_alg() |
          legacy_mac_alg().

max_idle_time_common_option()

-type max_idle_time_common_option() :: {idle_time, timeout()}.

Sets a time-out on a connection when no channels are open. Defaults to infinity. The unit is milliseconds.

The timeout is not active until channels are started, so it does not limit the time from the connection creation to the first channel opening.

For more information about timeouts, see the Timeouts section in the User's Guide Hardening chapter.

max_log_item_len_common_option()

-type max_log_item_len_common_option() :: {max_log_item_len, limit_bytes()}.

Sets a limit for the size of a logged item excluding a header. The unit is bytes and the value defaults to 500.

modify_algorithms_common_option()

-type modify_algorithms_common_option() :: {modify_algorithms, modify_algs_list()}.

modify_algs_list()

-type modify_algs_list() :: [{append, algs_list()} | {prepend, algs_list()} | {rm, algs_list()}].

Modifies the list of algorithms to use in the algorithm negotiation. The modifications are applied after the option preferred_algorithms (if existing) is applied.

The algorithm for modifications works like this:

Input is the modify_algs_list/0 and a set of algorithms A obtained from the preferred_algorithms option if existing, or else from the ssh:default_algorithms/0.

The head of the modify_algs_list/0 modifies A giving the result A'.

The possible modifications are:

Append or prepend supported but not enabled algorithm(s) to the list of algorithms. If the wanted algorithms already are in A they will first be removed and then appended or prepended,

Remove (rm) one or more algorithms from A.

Repeat the modification step with the tail of modify_algs_list/0 and the resulting A'.

If an unsupported algorithm is in the modify_algs_list/0, it will be silently ignored

If there are more than one modify_algorithms options, the result is undefined.

Here is an example of this option:

	  {modify_algorithms,
	  [{prepend, [{kex, ['diffie-hellman-group1-sha1']}],
	  {rm,      [{compression, [none]}]}
	  ]
	  }

The example specifies that:

the old key exchange algorithm 'diffie-hellman-group1-sha1' should be the main alternative. It will be the main alternative since it is prepened to the list

The compression algorithm none (= no compression) is removed so compression is enforced

For background and more examples see the User's Guide.

pref_public_key_algs_common_option()

-type pref_public_key_algs_common_option() :: {pref_public_key_algs, [pubkey_alg()]}.

List of user (client) public key algorithms to try to use.

The default value is the public_key entry in the list returned by ssh:default_algorithms/0.

If there is no public key of a specified type available, the corresponding entry is ignored. Note that the available set is dependent on the underlying cryptolib and current user's public keys.

See also the option user_dir for specifying the path to the user's keys.

preferred_algorithms_common_option()

-type preferred_algorithms_common_option() :: {preferred_algorithms, algs_list()}.

profile_common_option()

-type profile_common_option() :: {profile, atom()}.

Used together with ip-address and port to uniquely identify a ssh daemon. This can be useful in a virtualized environment, where there can be more that one server that has the same ip-address and port. If this property is not explicitly set, it is assumed that the the ip-address and port uniquely identifies the SSH daemon.

pubkey_alg()

-type pubkey_alg() ::
          'ecdsa-sha2-nistp256' | 'ecdsa-sha2-nistp384' | 'ecdsa-sha2-nistp521' | 'ssh-ed25519' |
          'ssh-ed448' | 'rsa-sha2-256' | 'rsa-sha2-512' |
          legacy_pubkey_alg().

rekey_limit_common_option()

-type rekey_limit_common_option() ::
          {rekey_limit, Bytes :: limit_bytes() | {Minutes :: limit_time(), Bytes :: limit_bytes()}}.

ssh_msg_debug_fun_common_option()

-type ssh_msg_debug_fun_common_option() ::
          {ssh_msg_debug_fun,
           fun((ssh:connection_ref(),
                AlwaysDisplay :: boolean(),
                Msg :: binary(),
                LanguageTag :: binary()) ->
                   any())}.

Provide a fun to implement your own logging of the SSH message SSH_MSG_DEBUG. The last three parameters are from the message, see RFC 4253, section 11.3. The connection_ref/0 is the reference to the connection on which the message arrived. The return value from the fun is not checked.

The default behaviour is ignore the message. To get a printout for each message with AlwaysDisplay = true, use for example {ssh_msg_debug_fun, fun(_,true,M,_)-> io:format("DEBUG: ~p~n", [M]) end}

unexpectedfun_common_option()

-type unexpectedfun_common_option() ::
          {unexpectedfun, fun((Message :: term(), {Host :: term(), Port :: term()}) -> report | skip)}.

Provides a fun to implement your own logging or other action when an unexpected message arrives. If the fun returns report the usual info report is issued but if skip is returned no report is generated.

Types: Daemon Options

authentication_daemon_options()

-type authentication_daemon_options() ::
          ssh_file:system_dir_daemon_option() |
          {auth_method_kb_interactive_data, prompt_texts()} |
          {user_passwords, [{UserName :: string(), Pwd :: string()}]} |
          {pk_check_user, boolean()} |
          {password, string()} |
          {pwdfun, pwdfun_2() | pwdfun_4()} |
          {no_auth_needed, boolean()}.

callbacks_daemon_options()

-type callbacks_daemon_options() ::
          {failfun,
           fun((User :: string(), Peer :: {inet:ip_address(), inet:port_number()}, Reason :: term()) ->
                   _)} |
          {connectfun,
           fun((User :: string(), Peer :: {inet:ip_address(), inet:port_number()}, Method :: string()) ->
                   _)} |
          {bannerfun, fun((User :: string()) -> binary())}.

connectfun - Provides a fun to implement your own logging when a user authenticates to the server.

failfun - Provides a fun to implement your own logging when a user fails to authenticate.

bannerfun - Provides a fun to implement the construction of a banner text that is sent at the beginning of the user authentication. The banner will not be sent if the function does not return a binary.

daemon_option()

-type daemon_option() ::
          subsystem_daemon_option() |
          shell_daemon_option() |
          exec_daemon_option() |
          ssh_cli_daemon_option() |
          tcpip_tunnel_out_daemon_option() |
          tcpip_tunnel_in_daemon_option() |
          authentication_daemon_options() |
          diffie_hellman_group_exchange_daemon_option() |
          max_initial_idle_time_daemon_option() |
          negotiation_timeout_daemon_option() |
          hello_timeout_daemon_option() |
          hardening_daemon_options() |
          callbacks_daemon_options() |
          send_ext_info_daemon_option() |
          gen_tcp:listen_option() |
          common_option() |
          experimental_daemon_options().

Options for daemons. The individual options are further explained below or by following the hyperlinks.

Note that not every gen_tcp:listen_option/0 is accepted. See set_sock_opts/2 for a list of prohibited options.

Also note that setting a gen_tcp:listen_option/0 could change the socket in a way that impacts the ssh deamon's behaviour negatively. You use it on your own risk.

daemon_options()

-type daemon_options() :: [daemon_option()].

deprecated_exec_opt()

-type deprecated_exec_opt() :: fun() | mod_fun_args().

Old-style exec specification that are kept for compatibility, but should not be used in new programs

diffie_hellman_group_exchange_daemon_option()

-type diffie_hellman_group_exchange_daemon_option() ::
          {dh_gex_groups, [explicit_group()] | explicit_group_file() | ssh_moduli_file()} |
          {dh_gex_limits, {Min :: pos_integer(), Max :: pos_integer()}}.

exec_daemon_option()

-type exec_daemon_option() :: {exec, exec_spec()}.

exec_fun()

-type exec_fun() :: 'exec_fun/1'() | 'exec_fun/2'() | 'exec_fun/3'().

The default is disabled.

Value erlang_eval enables evaluation of Erlang terms via exec requests. This works when the shell option is either disabled (no shell) or {shell, start, []} (Erlang shell). It does not work with custom shells.

To restore the behavior from OTP versions prior to OTP @OTP-19969@, configure:

ssh:daemon(Port, [{shell, {shell, start, []}},
                  {exec, erlang_eval}
                  | Options])

For new code, consider using {direct, Fun} for more controlled exec handling.

'exec_fun/1'()

-type 'exec_fun/1'() :: fun((Cmd :: string()) -> exec_result()).

'exec_fun/2'()

-type 'exec_fun/2'() :: fun((Cmd :: string(), User :: string()) -> exec_result()).

'exec_fun/3'()

-type 'exec_fun/3'() ::
          fun((Cmd :: string(), User :: string(), ClientAddr :: ip_port()) -> exec_result()).

exec_result()

-type exec_result() :: {ok, Result :: term()} | {error, Reason :: term()}.

This option changes how the daemon executes exec-requests from clients. The term in the return value is formatted to a string if it is a non-string type. No trailing newline is added in the ok-case.

See the User's Guide section on One-Time Execution for examples.

Error texts are returned on channel-type 1 which usually is piped to stderr on e.g Linux systems. Texts from a successful execution are returned on channel-type 0 and will in similar manner be piped to stdout. The exit-status code is set to 0 for success and 255 for errors. The exact results presented on the client side depends on the client and the client's operating system.

In case of the {direct, exec_fun()} variant or erlang_eval, all reads from standard_input will be from the received data-events of type 0. Those are sent by the client. Similarly all writes to standard_output will be sent as data-events to the client. An OS shell client like the command 'ssh' will usually use stdin and stdout for the user interface.

The option cooperates with the daemon-option shell in the following way:

1. If neither the exec-option nor the shell-option is present: - Both default to disabled. No exec-requests or shell-requests are executed. This is the default behavior since @OTP-19969@. To restore the previous behavior, set {shell, {shell, start, []}} and {exec, erlang_eval}.

2. If the exec_spec's value is disabled (the shell-option may or may not be present): - No exec-requests are executed but shell-requests are not affected, they follow the shell_spec's value.

3. If the exec-option is present and the exec_spec value =/= disabled (the shell-option may or may not be present): - The exec_spec fun() is called with the same number of parameters as the arity of the fun, and the result is returned to the client. Shell-requests are not affected, they follow the shell_spec's value.

4. If the exec_spec's value is erlang_eval, and the shell-option is disabled or set to the default Erlang shell {shell, start, []}: - The default Erlang evaluator is used for exec requests. The result is returned to the client. Shell-requests follow the shell_spec's value.

5. If the exec_spec's value is erlang_eval, and the shell-option is present with a value that is neither the default Erlang shell nor disabled: - The exec-request is not evaluated and an error message is returned to the client. Shell-requests are executed according to the value of the shell_spec.

6. If the exec-option is absent (defaults to disabled), and the shell_spec's value is disabled: - Neither exec-requests nor shell-requests are executed.

If a custom CLI is installed (see the option ssh_cli) the rules above are replaced by thoose implied by the custom CLI.

Note

The exec-option has existed for a long time but has not previously been documented. The old definition and behaviour are retained but obey the rules 1-6 above if conflicting. The old and undocumented style should not be used in new programs.

exec_spec()

-type exec_spec() :: {direct, exec_fun()} | disabled | deprecated_exec_opt() | erlang_eval.

explicit_group()

-type explicit_group() :: {Size :: pos_integer(), G :: pos_integer(), P :: pos_integer()}.

explicit_group_file()

-type explicit_group_file() :: {file, string()}.

hardening_daemon_options()

-type hardening_daemon_options() ::
          {max_sessions, pos_integer()} |
          {max_channels, pos_integer()} |
          {parallel_login, boolean()} |
          {minimal_remote_max_packet_size, pos_integer()}.

For more information about hardening, see the Hardening section in the User's Guide chapter.

max_sessions - The maximum number of simultaneous sessions that are accepted at any time for this daemon. This includes sessions that are being authorized. Thus, if set to N, and N clients have connected but not started the login process, connection attempt N+1 is aborted. If N connections are authenticated and still logged in, no more logins are accepted until one of the existing ones log out.

The counter is per listening port. Thus, if two daemons are started, one with {max_sessions,N} and the other with {max_sessions,M}, in total N+M connections are accepted for the whole ssh application.

Notice that if parallel_login is false, only one client at a time can be in the authentication phase.

By default, this option is not set. This means that the number is not limited.

max_channels - The maximum number of channels with active remote subsystem that are accepted for each connection to this daemon

By default, this option is not set. This means that the number is not limited.

parallel_login - If set to false (the default value), only one login is handled at a time. If set to true, an unlimited number of login attempts are allowed simultaneously.

If the max_sessions option is set to N and parallel_login is set to true, the maximum number of simultaneous login attempts at any time is limited to N-K, where K is the number of authenticated connections present at this daemon.

Warning

Do not enable parallel_logins without protecting the server by other means, for example, by the max_sessions option or a firewall configuration. If set to true, there is no protection against DOS attacks.

minimal_remote_max_packet_size - The least maximum packet size that the daemon will accept in channel open requests from the client. The default value is 0.

hello_timeout_daemon_option()

-type hello_timeout_daemon_option() :: {hello_timeout, timeout()}.

Maximum time in milliseconds for the first part of the ssh session setup, the hello message exchange. Defaults to 30000 ms (30 seconds). If the client fails to send the first message within this time, the connection is closed.

For more information about timeouts, see the Timeouts section in the User's Guide Hardening chapter.

kb_int_fun_3()

-type kb_int_fun_3() ::
          fun((Peer :: ip_port(), User :: string(), Service :: string()) -> kb_int_tuple()).

kb_int_fun_4()

-type kb_int_fun_4() ::
          fun((Peer :: ip_port(), User :: string(), Service :: string(), State :: any()) ->
                  kb_int_tuple()).

kb_int_tuple()

-type kb_int_tuple() ::
          {Name :: string(), Instruction :: string(), Prompt :: string(), Echo :: boolean()}.

max_initial_idle_time_daemon_option()

-type max_initial_idle_time_daemon_option() :: {max_initial_idle_time, timeout()}.

Maximum time in milliseconds for the first channel start after completion of the authentication negotiation. Defaults to infinity.

For more information about timeouts, see the Timeouts section in the User's Guide Hardening chapter.

negotiation_timeout_daemon_option()

-type negotiation_timeout_daemon_option() :: {negotiation_timeout, timeout()}.

Maximum time in milliseconds for the authentication negotiation. Defaults to 120000 ms (2 minutes). If the client fails to log in within this time, the connection is closed.

For more information about timeouts, see the Timeouts section in the User's Guide Hardening chapter.

prompt_texts()

-type prompt_texts() :: kb_int_tuple() | kb_int_fun_3() | kb_int_fun_4().

pwdfun_2()

-type pwdfun_2() :: fun((User :: string(), Password :: string() | pubkey) -> boolean()).

Equivalent to pwdfun_4/0.

pwdfun_4()

-type pwdfun_4() ::
          fun((User :: string(),
               Password :: string() | pubkey,
               PeerAddress :: ip_port(),
               State :: any()) ->
                  boolean() | disconnect | {boolean(), NewState :: any()}).

auth_method_kb_interactive_data - Sets the text strings that the daemon sends to the client for presentation to the user when using keyboard-interactive authentication.

If the fun/3 or fun/4 is used, it is called when the actual authentication occurs and may therefore return dynamic data like time, remote ip etc.

The parameter Echo guides the client about need to hide the password.

The default value is: {auth_method_kb_interactive_data, {"SSH server", "Enter password for \""++User++"\"", "password: ", false}>

user_passwords - Provides passwords for password authentication. The passwords are used when someone tries to connect to the server and public key user-authentication fails. The option provides a list of valid usernames and the corresponding passwords.

Warning

Note that this is very insecure due to the plain-text passwords; it is intended for test purposes. Use the pwdfun option to handle the password checking instead.

pk_check_user - Enables checking of the client's user name in the server when doing public key authentication. It is disabled by default.

The term "user" is used differently in OpenSSH and SSH in Erlang/OTP: see more in the User's Guide.

If the option is enabled, and no pwdfun is present, the user name must present in the user_passwords for the check to succeed but the value of the password is not checked.

In case of a pwdfun checking the user, the atom pubkey is put in the password argument.

password - Provides a global password that authenticates any user.

Warning

Intended to facilitate testing.

From a security perspective this option makes the server very vulnerable.

pwdfun with pwdfun_4/0 - Provides a function for password validation. This could used for calling an external system or handling passwords stored as hash values.

This fun can also be used to make delays in authentication tries for example by calling timer:sleep/1.

To facilitate for instance counting of failed tries, the State variable could be used. This state is per connection only. The first time the pwdfun is called for a connection, the State variable has the value undefined.

The fun should return:

true if the user and password is valid

false if the user or password is invalid

disconnect if a SSH_MSG_DISCONNECT message should be sent immediately. It will be followed by a close of the underlying tcp connection.

{true, NewState:any()} if the user and password is valid

{false, NewState:any()} if the user or password is invalid

A third usage is to block login attempts from a missbehaving peer. The State described above can be used for this. The return value disconnect is useful for this.

In case of the pk_check_user is set, the atom pubkey is put in the password argument when validating a public key login. The pwdfun is then responsible to check that the user name is valid.

pwdfun with pwdfun_2/0 - Provides a function for password validation. This function is called with user and password as strings, and returns:

true if the user and password is valid

false if the user or password is invalid

In case of the pk_check_user is set, the atom pubkey is put in the password argument when validating a public key login. The pwdfun is then responsible to check that the user name is valid.

This variant is kept for compatibility.

no_auth_needed - If true, a client is authenticated without any need of providing any password or key.

This option is only intended for very special applications due to the high risk of accepting any connecting client.

The default value is false.

send_ext_info_daemon_option()

-type send_ext_info_daemon_option() :: {send_ext_info, boolean()}.

Make the server (daemon) tell the client that the server accepts extension negotiation, that is, include ext-info-s in the kexinit message sent. See RFC 8308 for details and ssh for a list of currently implemented extensions.

Default value is true which is compatible with other implementations not supporting ext-info.

shell_daemon_option()

-type shell_daemon_option() :: {shell, shell_spec()}.

Equivalent to 'shell_fun/2'/0.

shell_fun()

-type shell_fun() :: 'shell_fun/1'() | 'shell_fun/2'().

The default is disabled.

To enable the Erlang shell:

ssh:daemon(Port, [{shell, {shell, start, []}} | Options])

'shell_fun/1'()

-type 'shell_fun/1'() :: fun((User :: string()) -> pid()).

Equivalent to 'shell_fun/2'/0.

'shell_fun/2'()

-type 'shell_fun/2'() :: fun((User :: string(), PeerAddr :: inet:ip_address()) -> pid()).

Defines the read-eval-print loop used in a daemon when a shell is requested by the client.

See the option exec-option for a description of how the daemon executes shell-requests and exec-requests depending on the shell- and exec-options.

shell_spec()

-type shell_spec() :: mod_fun_args() | shell_fun() | disabled.

ssh_cli_daemon_option()

-type ssh_cli_daemon_option() :: {ssh_cli, mod_args() | no_cli}.

Provides your own CLI implementation in a daemon.

It is a channel callback module that implements a shell and command execution. The shell's read-eval-print loop can be customized, using the option shell. This means less work than implementing an own CLI channel. If ssh_cli is set to no_cli, the CLI channels like shell and exec are disabled and only subsystem channels are allowed.

ssh_moduli_file()

-type ssh_moduli_file() :: {ssh_moduli_file, string()}.

dh_gex_groups - Defines the groups the server may choose among when diffie-hellman-group-exchange is negotiated. See RFC 4419 for details. The three variants of this option are:

{Size=integer(),G=integer(),P=integer()} - The groups are given explicitly in this list. There may be several elements with the same Size. In such a case, the server will choose one randomly in the negotiated Size.

{file,filename()} - The file must have one or more three-tuples {Size=integer(),G=integer(),P=integer()} terminated by a dot. The file is read when the daemon starts.

{ssh_moduli_file,filename()} - The file must be in ssh-keygen moduli file format. The file is read when the daemon starts.

The default list is fetched from the public_key application.

dh_gex_limits - Limits what a client can ask for in diffie-hellman-group-exchange. The limits will be {MaxUsed = min(MaxClient,Max), MinUsed = max(MinClient,Min)} where MaxClient and MinClient are the values proposed by a connecting client.

The default value is {0,infinity}.

If MaxUsed < MinUsed in a key exchange, it will fail with a disconnect.

See RFC 4419 for the function of the Max and Min values.

subsystem_daemon_option()

-type subsystem_daemon_option() :: {subsystems, subsystem_specs()}.

subsystem_spec()

-type subsystem_spec() :: {Name :: string(), mod_args()}.

Defines a subsystem in the daemon.

The subsystem_name is the name that a client requests to start with for example ssh_connection:subsystem/4.

The channel_callback is the module that implements the ssh_server_channel (replaces ssh_daemon_channel) behaviour in the daemon. See the section Creating a Subsystem in the User's Guide for more information and an example.

If the subsystems option is not present, the default is an empty list and no subsystems are enabled.

To enable the SFTP subsystem:

ssh:daemon(Port, [{subsystems, [ssh_sftpd:subsystem_spec([])]} | Options])

subsystem_specs()

-type subsystem_specs() :: [subsystem_spec()].

tcpip_tunnel_in_daemon_option()

-type tcpip_tunnel_in_daemon_option() ::
          {tcpip_tunnel_in,
           boolean() |
           (Callback :: fun((HostName :: string(), inet:port_number()) -> boolean() | denied))}.

Enables (true) or disables (false) the possibility to tunnel a TCP/IP connection in to a server. Disabled per default.

Set Callback function to allow/deny/log tunnel connections.

tcpip_tunnel_out_daemon_option()

-type tcpip_tunnel_out_daemon_option() :: {tcpip_tunnel_out, boolean()}.

Enables (true) or disables (false) the possibility to tunnel a TCP/IP connection out of a server. Disabled per default.

Types: Deprecated

ssh_channel_id()

-opaque ssh_channel_id()

ssh_connection_ref()

-opaque ssh_connection_ref()

ssh_daemon_ref()

-opaque ssh_daemon_ref()

Types: Legacy Algorithms

legacy_cipher_alg()

-type legacy_cipher_alg() :: 'aes128-cbc' | 'aes192-cbc' | 'aes256-cbc' | '3des-cbc'.

legacy_compression_alg()

This type is deprecated. use 'none' or 'zlib@openssh.com' instead.

-type legacy_compression_alg() :: zlib.

Deprecated: the use of zlib compression in SSH will be removed in OTP 30.0. Use none or zlib@openssh.com instead.

legacy_kex_alg()

-type legacy_kex_alg() ::
          'diffie-hellman-group1-sha1' | 'diffie-hellman-group14-sha1' |
          'diffie-hellman-group-exchange-sha1'.

legacy_mac_alg()

-type legacy_mac_alg() :: 'hmac-sha1-96'.

legacy_pubkey_alg()

-type legacy_pubkey_alg() :: 'ssh-rsa' | 'ssh-dss'.

Types

channel_id()

-opaque channel_id()

Opaque data type representing a channel inside a connection.

Returned by the functions ssh_connection:session_channel/2,4.

conn_info_algs()

-type conn_info_algs() ::
          [{kex, kex_alg()} |
           {hkey, pubkey_alg()} |
           {encrypt, cipher_alg()} |
           {decrypt, cipher_alg()} |
           {send_mac, mac_alg()} |
           {recv_mac, mac_alg()} |
           {compress, compression_alg()} |
           {decompress, compression_alg()} |
           {send_ext_info, boolean()} |
           {recv_ext_info, boolean()}].

conn_info_channels()

-type conn_info_channels() :: [proplists:proplist()].

connection_info_tuple()

-type connection_info_tuple() ::
          {client_version, version()} |
          {server_version, version()} |
          {user, string()} |
          {peer, {inet:hostname(), ip_port()}} |
          {sockname, ip_port()} |
          {options, client_options()} |
          {algorithms, conn_info_algs()} |
          {channels, conn_info_channels()}.

Return values from the connection_info/1 and connection_info/2 functions.

Note

Note that options info tuple contains only items with nondefault values.

connection_ref()

-type connection_ref() :: pid().

Opaque data type representing a connection between a client and a server (daemon).

Returned by the functions connect/2,3,4 and ssh_sftp:start_channel/2,3.

daemon_info_tuple()

-type daemon_info_tuple() ::
          {port, inet:port_number()} |
          {ip, inet:ip_address()} |
          {profile, atom()} |
          {options, daemon_options()}.

Return values from the daemon_info/1 and daemon_info/2 functions.

Note

Note that options info tuple contains only items with nondefault values.

daemon_ref()

-opaque daemon_ref()

Opaque data type representing a daemon.

Returned by the functions daemon/1,2,3.

experimental_client_options()

-type experimental_client_options() ::
          {keyboard_interact_fun,
           fun((Name :: iodata(),
                Instruction :: iodata(),
                Prompts :: [{Prompt :: iodata(), Echo :: boolean()}]) ->
                   [Response :: iodata()])} |
          experimental_common_options().

Experimental options that should not to be used in products.

experimental_common_options()

-type experimental_common_options() ::
          {transport, {atom(), atom(), atom()}} |
          {vsn, {non_neg_integer(), non_neg_integer()}} |
          {tstflg, [term()]} |
          ssh_file:user_dir_fun_common_option() |
          {max_random_length_padding, non_neg_integer()}.

Experimental options that should not to be used in products.

experimental_daemon_options()

-type experimental_daemon_options() :: {infofun, fun()} | experimental_common_options().

Experimental options that should not to be used in products.

host()

-type host() :: string() | inet:ip_address() | loopback.

ip_port()

-type ip_port() :: {inet:ip_address(), inet:port_number()}.

mod_args()

-type mod_args() :: {Module :: atom(), Args :: list()}.

mod_fun_args()

-type mod_fun_args() :: {Module :: atom(), Function :: atom(), Args :: list()}.

open_socket()

-type open_socket() :: gen_tcp:socket().

The socket is supposed to be result of a gen_tcp:connect or a gen_tcp:accept. The socket must be in passive mode (that is, opened with the option {active,false}).

protocol_version()

-type protocol_version() :: {Major :: pos_integer(), Minor :: non_neg_integer()}.

role()

-type role() :: client | server.

software_version()

-type software_version() :: string().

version()

-type version() :: {protocol_version(), software_version()}.

Functions

close(ConnectionRef)

-spec close(ConnectionRef) -> ok | {error, term()} when ConnectionRef :: connection_ref().

Closes an SSH connection.

connect(OpenTcpSocket, Options)

(since OTP 19.0)

-spec connect(OpenTcpSocket, Options) -> {ok, connection_ref()} | {error, term()}
                 when OpenTcpSocket :: open_socket(), Options :: client_options().

Equivalent to connect/4.

connect/3

-spec connect(open_socket(), client_options(), timeout()) -> {ok, connection_ref()} | {error, term()};
             (host(), inet:port_number(), client_options()) -> {ok, connection_ref()} | {error, term()}.

Equivalent to connect/4.

connect(Host, Port, Options, NegotiationTimeout)

-spec connect(Host, Port, Options, NegotiationTimeout) -> {ok, connection_ref()} | {error, term()}
                 when
                     Host :: host(),
                     Port :: inet:port_number(),
                     Options :: client_options(),
                     NegotiationTimeout :: timeout().

Connects to an SSH server at the Host on Port.

As an alternative, an already open TCP socket could be passed to the function in TcpSocket. The SSH initiation and negotiation will be initiated on that one with the SSH that should be at the other end.

No channel is started. This is done by calling ssh_connection:session_channel/2,4.

The NegotiationTimeout is in milli-seconds. The default value is infinity or the value of the connect_timeout option, if present. For connection timeout, use the option connect_timeout.

connection_info(ConnectionRef)

(since OTP 22.1)

-spec connection_info(ConnectionRef) -> InfoTupleList | {error, term()}
                         when
                             ConnectionRef :: connection_ref(),
                             InfoTupleList :: [InfoTuple],
                             InfoTuple :: connection_info_tuple().

Equivalent to connection_info/2.

connection_info(ConnectionRef, Key)

-spec connection_info(ConnectionRef, ItemList | Item) -> InfoTupleList | InfoTuple | {error, term()}
                         when
                             ConnectionRef :: connection_ref(),
                             ItemList :: [Item],
                             Item ::
                                 client_version | server_version | user | peer | sockname | options |
                                 algorithms | sockname,
                             InfoTupleList :: [InfoTuple],
                             InfoTuple :: connection_info_tuple().

Returns information about a connection intended for e.g debugging or logging.

When the Key is a single Item, the result is a single InfoTuple

daemon(Port)

-spec daemon(inet:port_number()) -> {ok, daemon_ref()} | {error, term()}.

Equivalent to daemon/3.

daemon/2

-spec daemon(inet:port_number() | open_socket(), daemon_options()) ->
                {ok, daemon_ref()} | {error, term()}.

Equivalent to daemon/3.

daemon(HostAddress, Port, Options)

-spec daemon(any | inet:ip_address(), inet:port_number(), daemon_options()) ->
                {ok, daemon_ref()} | {error, term()};
            (socket, open_socket(), daemon_options()) -> {ok, daemon_ref()} | {error, term()}.

Starts a server listening for SSH connections on the given port. If the Port is 0, a random free port is selected. See daemon_info/1 about how to find the selected port number.

As an alternative, an already open TCP socket could be passed to the function in TcpSocket. The SSH initiation and negotiation will be initiated on that one when an SSH starts at the other end of the TCP socket.

For a description of the options, see Daemon Options.

Please note that by historical reasons both the HostAddress argument and the gen_tcp connect_option() {ip,Address} set the listening address. This is a source of possible inconsistent settings.

The rules for handling the two address passing options are:

if HostAddress is an IP-address, that IP-address is the listening address. An 'ip'-option will be discarded if present.

if HostAddress is the atom loopback, the listening address is loopback and an loopback address will be chosen by the underlying layers. An 'ip'-option will be discarded if present.

if HostAddress is the atom any and no 'ip'-option is present, the listening address is any and the socket will listen to all addresses

if HostAddress is any and an 'ip'-option is present, the listening address is set to the value of the 'ip'-option

daemon_info(DaemonRef)

(since OTP 19.0)

-spec daemon_info(DaemonRef) -> {ok, InfoTupleList} | {error, bad_daemon_ref}
                     when
                         DaemonRef :: daemon_ref(),
                         InfoTupleList :: [InfoTuple],
                         InfoTuple :: daemon_info_tuple().

Equivalent to daemon_info/2.

daemon_info/2

(since OTP 22.1)

-spec daemon_info(DaemonRef, ItemList | Item) -> InfoTupleList | InfoTuple | {error, bad_daemon_ref}
                     when
                         DaemonRef :: daemon_ref(),
                         ItemList :: [Item],
                         Item :: ip | port | profile | options,
                         InfoTupleList :: [InfoTuple],
                         InfoTuple :: daemon_info_tuple().

Returns information about a daemon intended for e.g debugging or logging.

When the Key is a single Item, the result is a single InfoTuple

Note that daemon_info/1 and daemon_info/2 returns different types due to compatibility reasons.

daemon_replace_options(DaemonRef, NewUserOptions)

(since OTP 25.1)

-spec daemon_replace_options(DaemonRef, NewUserOptions) -> {ok, daemon_ref()} | {error, term()}
                                when DaemonRef :: daemon_ref(), NewUserOptions :: daemon_options().

Replaces the options in a running daemon with the options in NewUserOptions. Only connections established after this call are affected, already established connections are not.

Note

In the final phase of this function, the listening process is restarted. Therfore a connection attempt to the daemon in this final phase could fail.

The handling of Erlang configurations is described in the User's Guide; see chapters Configuration in SSH and Configuring algorithms in SSH.

default_algorithms()

(since OTP 18.0)

-spec default_algorithms() -> algs_list().

Returns a key-value list, where the keys are the different types of algorithms and the values are the algorithms themselves.

See the User's Guide for an example.

get_sock_opts(ConnectionRef, SocketGetOptions)

(since OTP 22.3)

-spec get_sock_opts(ConnectionRef, SocketGetOptions) -> ok | {error, inet:posix()}
                       when
                           ConnectionRef :: connection_ref(),
                           SocketGetOptions :: [gen_tcp:option_name()].

Get tcp socket option values of the tcp-socket below an ssh connection.

This function calls the inet:getopts/2, read that documentation.

hostkey_fingerprint(Key)

(since OTP 24.0)

-spec hostkey_fingerprint(public_key:public_key()) -> string().

Equivalent to hostkey_fingerprint/2.

hostkey_fingerprint(TypeOrTypes, Key)

(since OTP 24.0)

-spec hostkey_fingerprint(TypeOrTypes, Key) -> StringOrString
                             when
                                 TypeOrTypes :: public_key:digest_type() | [public_key:digest_type()],
                                 Key :: public_key:public_key(),
                                 StringOrString :: string() | [string()].

hostkey_fingerprint([DigestType], HostKey) -> [string()]hostkey_fingerprint(DigestType, HostKey) -> string()

Calculates a ssh fingerprint from a public host key as openssh does.

The algorithm in hostkey_fingerprint/1 is md5 to be compatible with older ssh-keygen commands. The string from the second variant is prepended by the algorithm name in uppercase as in newer ssh-keygen commands.

Examples:

 2> ssh:hostkey_fingerprint(Key).
 "f5:64:a6:c1:5a:cb:9f:0a:10:46:a2:5c:3e:2f:57:84"

 3> ssh:hostkey_fingerprint(md5,Key).
 "MD5:f5:64:a6:c1:5a:cb:9f:0a:10:46:a2:5c:3e:2f:57:84"

 4> ssh:hostkey_fingerprint(sha,Key).
 "SHA1:bSLY/C4QXLDL/Iwmhyg0PGW9UbY"

 5> ssh:hostkey_fingerprint(sha256,Key).
 "SHA256:aZGXhabfbf4oxglxltItWeHU7ub3Dc31NcNw2cMJePQ"

 6> ssh:hostkey_fingerprint([sha,sha256],Key).
 ["SHA1:bSLY/C4QXLDL/Iwmhyg0PGW9UbY",
  "SHA256:aZGXhabfbf4oxglxltItWeHU7ub3Dc31NcNw2cMJePQ"]

set_sock_opts(ConnectionRef, SocketOptions)

(since OTP 22.3)

-spec set_sock_opts(ConnectionRef, SocketOptions) -> ok | {error, inet:posix()}
                       when ConnectionRef :: connection_ref(), SocketOptions :: [gen_tcp:option()].

Sets tcp socket options on the tcp-socket below an ssh connection.

This function calls the inet:setopts/2, read that documentation and for gen_tcp:option/0.

All gen_tcp socket options except

active

deliver

mode and

packet

are allowed. The excluded options are reserved by the SSH application.

Warning

This is an extremely dangerous function. You use it on your own risk.

Some options are OS and OS version dependent. Do not use it unless you know what effect your option values will have on an TCP stream.

Some values may destroy the functionality of the SSH protocol.

shell/1

-spec shell(open_socket() | host() | connection_ref()) -> _.

Equivalent to shell/3.

shell(Dest, Options)

-spec shell(open_socket() | host(), client_options()) -> _.

Equivalent to shell/3.

shell(Host, Port, Options)

-spec shell(Host, Port, Options) -> _
               when Host :: host(), Port :: inet:port_number(), Options :: client_options().

Connects to an SSH server at Host and Port (defaults to 22) and starts an interactive shell on that remote host.

As an alternative, an already open TCP socket could be passed to the function in TcpSocket. The SSH initiation and negotiation will be initiated on that one and finally a shell will be started on the host at the other end of the TCP socket.

For a description of the options, see Client Options.

The function waits for user input, and does not return until the remote shell is ended (that is, exit from the shell).

start()

-spec start() -> ok | {error, term()}.

Equivalent to start/1.

start(Type)

-spec start(Type) -> ok | {error, term()} when Type :: permanent | transient | temporary.

Utility function that starts the applications crypto, public_key, and ssh. Default type is temporary. For more information, see the application manual page in Kernel.

stop()

-spec stop() -> ok | {error, term()}.

Stops the ssh application. For more information, see the application manual page in Kernel.

stop_daemon(DaemonRef)

-spec stop_daemon(DaemonRef :: daemon_ref()) -> ok.

Equivalent to stop_daemon/3.

stop_daemon(Address, Port)

-spec stop_daemon(inet:ip_address(), inet:port_number()) -> ok.

Equivalent to stop_daemon/3.

stop_daemon(Address, Port, Profile)

(since OTP 21.0)

-spec stop_daemon(any | inet:ip_address(), inet:port_number(), atom()) -> ok.

Stops the listener and all connections started by the listener.

If the daemon process does not exist, the call exits the calling process with reason noproc.

stop_listener(SysSup)

-spec stop_listener(daemon_ref()) -> ok.

Equivalent to stop_listener/3.

stop_listener(Address, Port)

-spec stop_listener(inet:ip_address(), inet:port_number()) -> ok.

Equivalent to stop_listener/3.

stop_listener(Address, Port, Profile)

(since OTP 21.0)

-spec stop_listener(any | inet:ip_address(), inet:port_number(), term()) -> ok.

Stops the listener, but leaves existing connections started by the listener operational.

tcpip_tunnel_from_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort)

(since OTP 23.0)

-spec tcpip_tunnel_from_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort) ->
                                  {ok, TrueListenPort} | {error, term()}
                                  when
                                      ConnectionRef :: connection_ref(),
                                      ListenHost :: host(),
                                      ListenPort :: inet:port_number(),
                                      ConnectToHost :: host(),
                                      ConnectToPort :: inet:port_number(),
                                      TrueListenPort :: inet:port_number().

Equivalent to tcpip_tunnel_from_server/6.

tcpip_tunnel_from_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort, Timeout)

(since OTP 23.0)

-spec tcpip_tunnel_from_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort,
                               Timeout) ->
                                  {ok, TrueListenPort} | {error, term()}
                                  when
                                      ConnectionRef :: connection_ref(),
                                      ListenHost :: host(),
                                      ListenPort :: inet:port_number(),
                                      ConnectToHost :: host(),
                                      ConnectToPort :: inet:port_number(),
                                      Timeout :: timeout(),
                                      TrueListenPort :: inet:port_number().

Asks the remote server of ConnectionRef to listen to ListenHost:ListenPort. When someone connects that address, the connection is forwarded in an encrypted channel from the server to the client. The client (that is, at the node that calls this function) then connects to ConnectToHost:ConnectToPort.

The returned TrueListenPort is the port that is listened to. It is the same as ListenPort, except when ListenPort = 0. In that case a free port is selected by the underlying OS.

Note that in case of an Erlang/OTP SSH server (daemon) as peer, that server must have been started with the option tcpip_tunnel_out to allow the connection.

tcpip_tunnel_to_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort)

(since OTP 23.0)

-spec tcpip_tunnel_to_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort) ->
                                {ok, TrueListenPort} | {error, term()}
                                when
                                    ConnectionRef :: connection_ref(),
                                    ListenHost :: host(),
                                    ListenPort :: inet:port_number(),
                                    ConnectToHost :: host(),
                                    ConnectToPort :: inet:port_number(),
                                    TrueListenPort :: inet:port_number().

Equivalent to tcpip_tunnel_to_server/6.

tcpip_tunnel_to_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort, Timeout)

(since OTP 23.0)

-spec tcpip_tunnel_to_server(ConnectionRef, ListenHost, ListenPort, ConnectToHost, ConnectToPort,
                             Timeout) ->
                                {ok, TrueListenPort} | {error, term()}
                                when
                                    ConnectionRef :: connection_ref(),
                                    ListenHost :: host(),
                                    ListenPort :: inet:port_number(),
                                    ConnectToHost :: host(),
                                    ConnectToPort :: inet:port_number(),
                                    Timeout :: timeout(),
                                    TrueListenPort :: inet:port_number().

Tells the local client to listen to ListenHost:ListenPort. When someone connects to that address, the connection is forwarded in an encrypted channel to the peer server of ConnectionRef. That server then connects to ConnectToHost:ConnectToPort.

The returned TrueListenPort is the port that is listened to. It is the same as ListenPort, except when ListenPort = 0. In that case a free port is selected by the underlying OS.

Note that in case of an Erlang/OTP SSH server (daemon) as peer, that server must have been started with the option tcpip_tunnel_in to allow the connection.

ssh_agent

Callback module for using an SSH agent instead of the default ssh_file callback.

This module defines a callback handler for the communication with an SSH Agent and can be used to replace the default callback. This allows to issue signing requests to an agent that stores SSH private keys to perform authentication.

Ssh_agent implements the ssh_client_key_api, to allow it to be used by setting the option key_cb when starting a client (with for example ssh:connect, ssh:shell ).

      {key_cb, {ssh_agent, []}}

The agent communication is established through a UNIX domain socket. By default, the socket path will be fetched from the SSH_AUTH_SOCK environment variable, which is the default socket path in the agent implementation of OpenSSH.

In order to set a different socket path the socket_path option can be set.

      {key_cb, {ssh_agent, [{socket_path, SocketPath}]}}

Note

The functions are Callbacks for the SSH application. They are not intended to be called from the user's code!

Summary

Types: Options

call_ssh_file_option()

The module which the add_host_key and is_host_key callbacks are delegated to. Defaults to the ssh_file module.

socket_path_option()

Sets the socket path for the communication with the agent.

timeout_option()

Sets the time-out in milliseconds when communicating with the agent via the socket. The default value is 1000.

Functions

add_host_key(Host, PublicKey, Options)

Equivalent to add_host_key/4.

add_host_key(Host, Port, PublicKey, Options)

This callback is delegated to the ssh_file module.

is_host_key(Key, Host, Algorithm, Options)

Equivalent to is_host_key/5.

is_host_key(Key, PeerName, Port, Algorithm, Opts)

This callback is delegated to the ssh_file module.

user_key(Algorithm, Options)

Types and description

Types: Options

call_ssh_file_option()

(since OTP 23.0)

-type call_ssh_file_option() :: {call_ssh_file, atom()}.

The module which the add_host_key and is_host_key callbacks are delegated to. Defaults to the ssh_file module.

socket_path_option()

(since OTP 23.0)

-type socket_path_option() :: {socket_path, string()}.

Sets the socket path for the communication with the agent.

timeout_option()

(since OTP 23.0)

-type timeout_option() :: {timeout, timeout()}.

Sets the time-out in milliseconds when communicating with the agent via the socket. The default value is 1000.

Functions

add_host_key(Host, PublicKey, Options)

(since OTP 23.0)

-spec add_host_key(string(), public_key:public_key(), Options) -> ok | {error, Error :: term()}
                      when Options :: ssh_client_key_api:client_key_cb_options(call_ssh_file_option()).

Equivalent to add_host_key/4.

add_host_key(Host, Port, PublicKey, Options)

(since OTP 23.0)

-spec add_host_key(Host, inet:port_number(), public_key:public_key(), Options) -> Result
                      when
                          Host ::
                              inet:ip_address() |
                              inet:hostname() |
                              [inet:ip_address() | inet:hostname()],
                          Options :: ssh_client_key_api:client_key_cb_options(call_ssh_file_option()),
                          Result :: ok | {error, Error :: term()}.

This callback is delegated to the ssh_file module.

is_host_key(Key, Host, Algorithm, Options)

(since OTP 23.0)

-spec is_host_key(Key :: public_key:public_key(),
                  Host :: string(),
                  Algorithm :: ssh:pubkey_alg(),
                  Options) ->
                     boolean()
                     when Options :: ssh_client_key_api:client_key_cb_options(call_ssh_file_option()).

Equivalent to is_host_key/5.

is_host_key(Key, PeerName, Port, Algorithm, Opts)

(since OTP 23.0)

-spec is_host_key(public_key:public_key(), Host, inet:port_number(), ssh:pubkey_alg(), Options) ->
                     boolean()
                     when
                         Host ::
                             inet:ip_address() | inet:hostname() | [inet:ip_address() | inet:hostname()],
                         Options :: ssh_client_key_api:client_key_cb_options(call_ssh_file_option()).

This callback is delegated to the ssh_file module.

user_key(Algorithm, Options)

(since OTP 23.0)

-spec user_key(Algorithm :: ssh:pubkey_alg(), Options) -> Result
                  when
                      Result ::
                          {ok, public_key:private_key()} |
                          {ok, {ssh2_pubkey, PubKeyBlob :: binary()}} |
                          {error, string()},
                      Options ::
                          ssh_client_key_api:client_key_cb_options(socket_path_option() |
                                                                   timeout_option()).

Types and description

See the api description in ssh_client_key_api, Module:user_key/2.

ssh_client_channel behaviour

SSH services (clients and servers) are implemented as channels that are multiplexed over an SSH connection and communicates over the SSH Connection Protocol. This module provides a callback API that takes care of generic channel aspects for clients, such as flow control and close messages. It lets the callback functions take care of the service (application) specific parts. This behavior also ensures that the channel process honors the principal of an OTP-process so that it can be part of a supervisor tree. This is a requirement of channel processes implementing a subsystem that will be added to the ssh applications supervisor tree.

Note

This module replaces ssh_channel.

The old module is still available for compatibility, but should not be used for new programs. The old module will not be maintained except for some error corrections

Note

When implementing a ssh subsystem for daemons, use -behaviour(ssh_server_channel) (Replaces ssh_daemon_channel) instead.

Dont

Functions in this module are not supposed to be called outside a module implementing this behaviour!

Callback timeouts

The timeout values that can be returned by the callback functions have the same semantics as in a gen_server. If the time-out occurs, handle_msg/2 is called as handle_msg(timeout, State).

Summary

Types

client()

Callbacks

code_change(OldVsn, State, Extra)

Converts process state when code is changed.

handle_call(Request, From, State)

Handles messages sent by calling call/2,3

handle_cast(Request, State)

Handles messages sent by calling cast/2.

handle_msg(Msg, State)

Handles other messages than SSH Connection Protocol, call, or cast messages sent to the channel.

handle_ssh_msg/2

Handles SSH Connection Protocol messages that may need service-specific attention. For details, see ssh_connection:event/0.

init(Args)

Makes necessary initializations and returns the initial channel state if the initializations succeed.

terminate(Reason, State)

This function is called by a channel process when it is about to terminate. Before this function is called, ssh_connection:close/2 is called, if it has not been called earlier. This function does any necessary cleaning up. When it returns, the channel process terminates with reason Reason. The return value is ignored.

Functions

call(ChannelRef, Msg)

Equivalent to call/3.

call(ChannelRef, Msg, Timeout)

Makes a synchronous call to the channel process by sending a message and waiting until a reply arrives, or a time-out occurs. The channel calls Module:handle_call/3 to handle the message. If the channel process does not exist, {error, closed} is returned.

cast(ChannelRef, Msg)

Sends an asynchronous message to the channel process and returns ok immediately, ignoring if the destination node or channel process does not exist. The channel calls Module:handle_cast/2 to handle the message.

enter_loop(State)

Makes an existing process an ssh_client_channel (replaces ssh_channel) process.

init(Args)

Initiates a client channel.

reply(Client, Reply)

This function can be used by a channel to send a reply to a client that called call/[2,3] when the reply cannot be defined in the return value of Module:handle_call/3.

start(SshConnection, ChannelId, ChannelCb, CbInitArgs)

Equivalent to start_link/4.

start_link(SshConnection, ChannelId, ChannelCb, CbInitArgs)

Starts a process that handles an SSH channel. It is called internally, by the ssh daemon, or explicitly by the ssh client implementations. The behavior sets the trap_exit flag to true.

Types

client()

(since OTP 21.0)

-opaque client()

Callbacks

code_change(OldVsn, State, Extra)

(since OTP 21.0)

-callback code_change(OldVsn :: term() | {down, term()}, State :: term(), Extra :: term()) ->
                         {ok, NewState :: term()} | {error, Reason :: term()}.

Converts process state when code is changed.

This function is called by a client-side channel when it is to update its internal state during a release upgrade or downgrade, that is, when the instruction {update,Module,Change,...}, where Change={advanced,Extra}, is given in the appup file. For more information, refer to Section 9.11.6 Release Handling Instructions in the System Documentation.

Note

Soft upgrade according to the OTP release concept is not straight forward for the server side, as subsystem channel processes are spawned by the ssh application and hence added to its supervisor tree. The subsystem channels can be upgraded when upgrading the user application, if the callback functions can handle two versions of the state, but this function cannot be used in the normal way.

handle_call(Request, From, State)

(since OTP 21.0)

-callback handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: term()) ->
                         {reply, Reply :: term(), NewState :: term()} |
                         {reply, Reply :: term(), NewState :: term(), timeout() | hibernate} |
                         {noreply, NewState :: term()} |
                         {noreply, NewState :: term(), timeout() | hibernate} |
                         {stop, Reason :: term(), Reply :: term(), NewState :: term()} |
                         {stop, Reason :: term(), NewState :: term()}.

Handles messages sent by calling call/2,3

For more detailed information on time-outs,, see Section Callback timeouts.

handle_cast(Request, State)

(since OTP 21.0)

-callback handle_cast(Request :: term(), State :: term()) ->
                         {noreply, NewState :: term()} |
                         {noreply, NewState :: term(), timeout() | hibernate} |
                         {stop, Reason :: term(), NewState :: term()}.

Handles messages sent by calling cast/2.

For more detailed information on time-outs, see Section Callback timeouts.

handle_msg(Msg, State)

(since OTP 21.0)

-callback handle_msg(Msg :: term(), State :: term()) ->
                        {ok, State :: term()} | {stop, ChannelId :: ssh:channel_id(), State :: term()}.

Handles other messages than SSH Connection Protocol, call, or cast messages sent to the channel.

Possible Erlang 'EXIT' messages is to be handled by this function and all channels are to handle the following message.

{ssh_channel_up, ssh:channel_id/0 , ssh:connection_ref/0 } - This is the first message that the channel receives. It is sent just before the init/1 function returns successfully. This is especially useful if the server wants to send a message to the client without first receiving a message from it. If the message is not useful for your particular scenario, ignore it by immediately returning {ok, State}.

handle_ssh_msg/2

(since OTP 21.0)

-callback handle_ssh_msg(ssh_connection:event(), State :: term()) ->
                            {ok, State :: term()} | {stop, ChannelId :: ssh:channel_id(), State :: term()}.

Handles SSH Connection Protocol messages that may need service-specific attention. For details, see ssh_connection:event/0.

The following message is taken care of by the ssh_client_channel behavior.

{closed, ssh:channel_id/0 } - The channel behavior sends a close message to the other side, if such a message has not already been sent. Then it terminates the channel with reason normal.

init(Args)

(since OTP 21.0)

-callback init(Args :: term()) ->
                  {ok, State :: term()} |
                  {ok, State :: term(), timeout() | hibernate} |
                  {stop, Reason :: term()} |
                  ignore.

Makes necessary initializations and returns the initial channel state if the initializations succeed.

For more detailed information on time-outs, see Section Callback timeouts.

terminate(Reason, State)

(since OTP 21.0)

-callback terminate(Reason :: normal | shutdown | {shutdown, term()} | term(), State :: term()) -> term().

This function is called by a channel process when it is about to terminate. Before this function is called, ssh_connection:close/2 is called, if it has not been called earlier. This function does any necessary cleaning up. When it returns, the channel process terminates with reason Reason. The return value is ignored.

Functions

call(ChannelRef, Msg)

(since OTP 21.0)

-spec call(ChannelRef, Msg) -> Reply | {error, Reason}
              when ChannelRef :: pid(), Msg :: term(), Reply :: term(), Reason :: closed | timeout.

Equivalent to call/3.

call(ChannelRef, Msg, Timeout)

(since OTP 21.0)

-spec call(ChannelRef, Msg, Timeout) -> Reply | {error, Reason}
              when
                  ChannelRef :: pid(),
                  Msg :: term(),
                  Timeout :: timeout(),
                  Reply :: term(),
                  Reason :: closed | timeout.

Makes a synchronous call to the channel process by sending a message and waiting until a reply arrives, or a time-out occurs. The channel calls Module:handle_call/3 to handle the message. If the channel process does not exist, {error, closed} is returned.

cast(ChannelRef, Msg)

(since OTP 21.0)

-spec cast(ChannelRef, Msg) -> ok when ChannelRef :: pid(), Msg :: term().

Sends an asynchronous message to the channel process and returns ok immediately, ignoring if the destination node or channel process does not exist. The channel calls Module:handle_cast/2 to handle the message.

enter_loop(State)

(since OTP 21.0)

-spec enter_loop(State) -> no_return() when State :: term().

Makes an existing process an ssh_client_channel (replaces ssh_channel) process.

Does not return, instead the calling process enters the ssh_client_channel (replaces ssh_channel) process receive loop and become an ssh_client_channel process. The process must have been started using one of the start functions in proc_lib, see the proc_lib manual page in STDLIB. The user is responsible for any initialization of the process and must call init/1.

init(Args)

(since OTP 21.0)

-spec init(Args) -> {ok, State} | {ok, State, Timeout} | {stop, Reason}
              when
                  Args :: [[{Option :: term(), Value :: term()}]],
                  State :: term(),
                  Timeout :: timeout(),
                  Reason :: term().

Initiates a client channel.

The following options must be present:

{channel_cb, atom()} - The module that implements the channel behaviour.

{init_args(), term()} - The arguments to the init function of the callback module.

{cm, ssh:connection_ref/0 } - Reference to the ssh connection as returned by ssh:connect/3.

{channel_id, ssh:channel_id/0 } - Id of the ssh channel as returned by ssh_connection:session_channel/2,4.

Note

This function is normally not called by the user. The user only needs to call if the channel process needs to be started with help of proc_lib instead of calling start/4 or start_link/4.

reply(Client, Reply)

(since OTP 21.0)

-spec reply(Client, Reply) -> _ when Client :: client(), Reply :: term().

This function can be used by a channel to send a reply to a client that called call/[2,3] when the reply cannot be defined in the return value of Module:handle_call/3.

Client must be the From argument provided to the callback function handle_call/3. Reply is an arbitrary term, which is given back to the client as the return value of [call/[2,3].](call/2)

start(SshConnection, ChannelId, ChannelCb, CbInitArgs)

(since OTP 21.0)

-spec start(SshConnection, ChannelId, ChannelCb, CbInitArgs) ->
               {ok, ChannelRef} | {error, Reason :: term()}
               when
                   SshConnection :: ssh:connection_ref(),
                   ChannelId :: ssh:channel_id(),
                   ChannelCb :: atom(),
                   CbInitArgs :: term(),
                   ChannelRef :: pid().

Equivalent to start_link/4.

start_link(SshConnection, ChannelId, ChannelCb, CbInitArgs)

(since OTP 21.0)

-spec start_link(SshConnection, ChannelId, ChannelCb, CbInitArgs) ->
                    {ok, ChannelRef} | {error, Reason :: term()}
                    when
                        SshConnection :: ssh:connection_ref(),
                        ChannelId :: ssh:channel_id(),
                        ChannelCb :: atom(),
                        CbInitArgs :: term(),
                        ChannelRef :: pid().

Starts a process that handles an SSH channel. It is called internally, by the ssh daemon, or explicitly by the ssh client implementations. The behavior sets the trap_exit flag to true.

The CbInitArgs parameter can be any Erlang term and will be passed as-is to the callback module's init/1 function. Common patterns include:

A list of parameters: [Param1, Param2, ...]

A map: #{key => value}

A single value: an atom, tuple, or other term

ssh_client_key_api behaviour

-behaviour(ssh_client_key_api).

Behavior describing the API for public key handling of an SSH client. By implementing the callbacks defined in this behavior, the public key handling of an SSH client can be customized. By default the ssh application implements this behavior with help of the standard OpenSSH files, see the ssh application manual.

Summary

Types

client_key_cb_options(T)

Options provided to ssh:connect/3,4.

Callbacks

add_host_key(Host, PublicKey, Options)

This function is retired in favour for Module:add_host_key/4 which is the preferred API function. The calling SSH application will still try the add_host_key/3 if the call to add_host_key/4 failed.

add_host_key(Host, Port, PublicKey, Options)

Adds a host key to the set of trusted host keys.

is_host_key(Key, Host, Algorithm, Options)

This function is retired in favour for Module:is_host_key/5 which is the preferred API function. The calling SSH application will still try the is_host_key/4 if the call to is_host_key/5 failed.

is_host_key(Key, Host, Port, Algorithm, Options)

Checks if a host key is trusted.

sign(PubKeyBlob, SigData, Options)

Sign the SigData with the private key corresponding to PubKeyBlob.

user_key(Algorithm, Options)

Fetches the users public key matching the Algorithm. Some key callback modules may return {ssh2_pubkey, PubKeyBlob :: binary()}.

Types

client_key_cb_options(T)

(since OTP R16B)

-type client_key_cb_options(T) :: [{key_cb_private, [T]} | ssh:client_option()].

Options provided to ssh:connect/3,4.

The option list given in the key_cb option is available with the key key_cb_private.

Callbacks

add_host_key(Host, PublicKey, Options)

(since OTP R16B) (optional)

-callback add_host_key(Host :: string(),
                       PublicKey :: public_key:public_key(),
                       Options :: client_key_cb_options(any())) ->
                          ok | {error, term()}.

This function is retired in favour for Module:add_host_key/4 which is the preferred API function. The calling SSH application will still try the add_host_key/3 if the call to add_host_key/4 failed.

Adds a host key to the set of trusted host keys.

add_host_key(Host, Port, PublicKey, Options)

(since OTP R16B) (optional)

-callback add_host_key(Host :: inet:ip_address() | inet:hostname() | [inet:ip_address() | inet:hostname()],
                       Port :: inet:port_number(),
                       PublicKey :: public_key:public_key(),
                       Options :: client_key_cb_options(any())) ->
                          ok | {error, term()}.

Adds a host key to the set of trusted host keys.

This function is preferred to the old Module:add_host_key/3 since it also uses the peer host port number and may return an error message.

The OTP/SSH application first calls this function in the callback module, and then the old Module:add_host_key/3 for compatibility.

is_host_key(Key, Host, Algorithm, Options)

(since OTP R16B) (optional)

-callback is_host_key(Key :: public_key:public_key(),
                      Host :: string(),
                      Algorithm :: ssh:pubkey_alg(),
                      Options :: client_key_cb_options(any())) ->
                         boolean().

This function is retired in favour for Module:is_host_key/5 which is the preferred API function. The calling SSH application will still try the is_host_key/4 if the call to is_host_key/5 failed.

Checks if a host key is trusted.

is_host_key(Key, Host, Port, Algorithm, Options)

(since OTP 23.0) (optional)

-callback is_host_key(Key :: public_key:public_key(),
                      Host :: inet:ip_address() | inet:hostname() | [inet:ip_address() | inet:hostname()],
                      Port :: inet:port_number(),
                      Algorithm :: ssh:pubkey_alg(),
                      Options :: client_key_cb_options(any())) ->
                         boolean() | {error, term()}.

Checks if a host key is trusted.

This function is preferred to the old Module:is_host_key/4 since it also uses the peer host port number and may return an error message.

The OTP/SSH application first calls this function in the callback module, and then the old Module:is_host_key/4 for compatibility.

sign(PubKeyBlob, SigData, Options)

(since OTP 23.0) (optional)

-callback sign(PubKeyBlob :: binary(), SigData :: binary(), Options :: client_key_cb_options(any())) ->
                  Blob :: binary().

Sign the SigData with the private key corresponding to PubKeyBlob.

user_key(Algorithm, Options)

(since OTP R16B)

-callback user_key(Algorithm :: ssh:pubkey_alg(), Options :: client_key_cb_options(any())) ->
                      {ok, public_key:private_key()} |
                      {ok, {ssh2_pubkey, PubKeyBlob :: binary()}} |
                      {error, string()}.

Fetches the users public key matching the Algorithm. Some key callback modules may return {ssh2_pubkey, PubKeyBlob :: binary()}.

Note

The private key contains the public key.

ssh_connection

This module provides API functions to send SSH Connection Protocol events to the other side of an SSH channel.

The SSH Connection Protocol (RFC 4254) is used by clients and servers, that is, SSH channels, to communicate over the SSH connection. The API functions in this module send SSH Connection Protocol events, which are received as messages by the remote channel handling the remote channel. The Erlang format of thoose messages is (see also below):

{ssh_cm, ssh:connection_ref/0 , channel_msg/0 }

If the ssh_client_channel behavior is used to implement the channel process, these messages are handled by handle_ssh_msg/2.

Summary

Types: Closing a Channel

closed_ch_msg()

This event is sent as a result of calling ssh_connection:close/2. Both the handling of this event and sending it are taken care of by the ssh_client_channel behavior.

eof_ch_msg()

Indicates that the other side sends no more data. This event is sent as a result of calling ssh_connection:send_eof/2.

Types: Data Transfer

data_ch_msg()

Data has arrived on the channel. This event is sent as a result of calling ssh_connection:send/3,4,5.

Types: Environment Variable

env_ch_msg()

Environment variables can be passed to the shell/command to be started later. This event is sent as a result of calling ssh_connection:setenv/5.

Types: Exit Status

exit_signal_ch_msg()

A remote execution can terminate violently because of a signal. Then this message can be received. For details on valid string values, see RFC 4254 Section 6.10, which shows a special case of these signals.

exit_status_ch_msg()

When the command running at the other end terminates, the following message can be sent to return the exit status of the command. A zero exit_status usually means that the command terminated successfully. This event is sent as a result of calling ssh_connection:exit_status/3.

Types: General

channel_msg()

As mentioned in the introduction, the SSH Connection Protocol events are handled as messages. When writing a channel handling process without using the support by the ssh_client_channel behavior the process must handle thoose messages.

event()

want_reply()

Messages that include a WantReply expect the channel handling process to call ssh_connection:reply_request/4 with the boolean value of WantReply as the second argument.

Types: Pseudo-Terminal

pty_ch_msg()

term_mode()

A pseudo-terminal has been requested for the session. Terminal is the value of the TERM environment variable value, that is, vt100. Zero dimension parameters must be ignored. The character/row dimensions override the pixel dimensions (when non-zero). Pixel dimensions refer to the drawable area of the window. Opcode in the TerminalModes list is the mnemonic name, represented as a lowercase Erlang atom, defined in RFC 4254, Section 8. It can also be an Opcode if the mnemonic name is not listed in the RFC. Example: OP code: 53, mnemonic name ECHO erlang atom: echo. This event is sent as a result of calling ssh_connection:ptty_alloc/4.

Types: Shell or Command

exec_ch_msg()

This message requests that the server starts execution of the given command. This event is sent as a result of calling ssh_connection:exec/4 .

shell_ch_msg()

This message requests that the user default shell is started at the other end. This event is sent as a result of calling ssh_connection:shell/2.

Types: Signals

signal_ch_msg()

A signal can be delivered to the remote process/service using the following message. Some systems do not support signals, in which case they are to ignore this message. There is currently no function to generate this event as the signals referred to are on OS-level and not something generated by an Erlang program.

Types: Window Change

window_change_ch_msg()

When the window (terminal) size changes on the client side, it can send a message to the server side to inform it of the new dimensions. No API function generates this event.

Types

channel_id()

connection_ref()

reason()

The result of a call.

req_status()

The status of a request. Corresponds to the SSH_MSG_CHANNEL_SUCCESS and SSH_MSG_CHANNEL_FAILURE values in RFC 4254, Section 5.4.

result()

ssh_data_type_code()

The valid values are 0 ("normal") and 1 ("stderr"), see RFC 4254, Section 5.2.

Functions

adjust_window(ConnectionRef, ChannelId, NumOfBytes)

Adjusts the SSH flow control window. This is to be done by both the client- and server-side channel processes.

close(ConnectionRef, ChannelId)

A server- or client-channel process can choose to close their session by sending a close event.

exec(ConnectionRef, ChannelId, Command, Timeout)

Is to be called by a client-channel process to request that the server starts executing the given command. The result is several messages according to the following pattern. The last message is a channel close message, as the exec request is a one-time execution that closes the channel when it is done.

exit_status(ConnectionRef, ChannelId, Status)

Is to be called by a server-channel process to send the exit status of a command to the client.

ptty_alloc(ConnectionRef, ChannelId, Options)

Equivalent to ptty_alloc/4.

ptty_alloc(ConnectionRef, ChannelId, Options, Timeout)

Sends an SSH Connection Protocol pty_req, to allocate a pseudo-terminal. Is to be called by an SSH client process.

reply_request(ConnectionRef, WantReply, Status, ChannelId)

Sends status replies to requests where the requester has stated that it wants a status report, that is, WantReply = true. If WantReply is false, calling this function becomes a "noop". Is to be called while handling an SSH Connection Protocol message containing a WantReply boolean value.

send(ConnectionRef, ChannelId, Data)

Equivalent to send/5.

send(ConnectionRef, ChannelId, Type, Data)

Depending on input arguments equivalent to one of send/5 calls specified below.

send(ConnectionRef, ChannelId, Type, Data, TimeOut)

Is to be called by client- and server-channel processes to send data to each other.

send_eof(ConnectionRef, ChannelId)

Sends EOF on channel ChannelId.

session_channel(ConnectionRef, Timeout)

Equivalent to session_channel/4.

session_channel(ConnectionRef, InitialWindowSize, MaxPacketSize, Timeout)

Opens a channel for an SSH session. The channel id returned from this function is the id used as input to the other functions in this module.

setenv(ConnectionRef, ChannelId, Var, Value, Timeout)

Environment variables can be passed before starting the shell/command. Is to be called by a client channel processes.

shell(ConnectionRef, ChannelId)

Is to be called by a client channel process to request that the user default shell (typically defined in /etc/passwd in Unix systems) is executed at the server end.

subsystem(ConnectionRef, ChannelId, Subsystem, Timeout)

Is to be called by a client-channel process for requesting to execute a predefined subsystem on the server.

Types: Closing a Channel

closed_ch_msg()

(RFC 4254, section 5.3)

-type closed_ch_msg() :: {closed, ssh:channel_id()}.

This event is sent as a result of calling ssh_connection:close/2. Both the handling of this event and sending it are taken care of by the ssh_client_channel behavior.

eof_ch_msg()

(RFC 4254, section 5.3)

-type eof_ch_msg() :: {eof, ssh:channel_id()}.

Indicates that the other side sends no more data. This event is sent as a result of calling ssh_connection:send_eof/2.

Types: Data Transfer

data_ch_msg()

(RFC 4254, section 5.2)

-type data_ch_msg() :: {data, ssh:channel_id(), ssh_data_type_code(), Data :: binary()}.

Data has arrived on the channel. This event is sent as a result of calling ssh_connection:send/3,4,5.

Types: Environment Variable

env_ch_msg()

(RFC 4254, section 6.4)

-type env_ch_msg() :: {env, ssh:channel_id(), want_reply(), Var :: string(), Value :: string()}.

Environment variables can be passed to the shell/command to be started later. This event is sent as a result of calling ssh_connection:setenv/5.

Types: Exit Status

exit_signal_ch_msg()

(RFC 4254, section 6.10)

-type exit_signal_ch_msg() ::
          {exit_signal,
           ssh:channel_id(),
           ExitSignal :: string(),
           ErrorMsg :: string(),
           LanguageString :: string()}.

A remote execution can terminate violently because of a signal. Then this message can be received. For details on valid string values, see RFC 4254 Section 6.10, which shows a special case of these signals.

exit_status_ch_msg()

(RFC 4254, section 6.10)

-type exit_status_ch_msg() :: {exit_status, ssh:channel_id(), ExitStatus :: non_neg_integer()}.

When the command running at the other end terminates, the following message can be sent to return the exit status of the command. A zero exit_status usually means that the command terminated successfully. This event is sent as a result of calling ssh_connection:exit_status/3.

Types: General

channel_msg()

-type channel_msg() ::
          data_ch_msg() |
          eof_ch_msg() |
          closed_ch_msg() |
          pty_ch_msg() |
          env_ch_msg() |
          shell_ch_msg() |
          exec_ch_msg() |
          signal_ch_msg() |
          window_change_ch_msg() |
          exit_status_ch_msg() |
          exit_signal_ch_msg().

As mentioned in the introduction, the SSH Connection Protocol events are handled as messages. When writing a channel handling process without using the support by the ssh_client_channel behavior the process must handle thoose messages.

event()

-type event() :: {ssh_cm, ssh:connection_ref(), channel_msg()}.

want_reply()

-type want_reply() :: boolean().

Messages that include a WantReply expect the channel handling process to call ssh_connection:reply_request/4 with the boolean value of WantReply as the second argument.

Types: Pseudo-Terminal

pty_ch_msg()

(RFC 4254, section 6.2)

-type pty_ch_msg() ::
          {pty,
           ssh:channel_id(),
           want_reply(),
           {Terminal :: string(),
            CharWidth :: non_neg_integer(),
            RowHeight :: non_neg_integer(),
            PixelWidth :: non_neg_integer(),
            PixelHeight :: non_neg_integer(),
            TerminalModes :: [term_mode()]}}.

term_mode()

(RFC 4254, section 6.2)

-type term_mode() :: {Opcode :: atom() | byte(), Value :: non_neg_integer()}.

A pseudo-terminal has been requested for the session. Terminal is the value of the TERM environment variable value, that is, vt100. Zero dimension parameters must be ignored. The character/row dimensions override the pixel dimensions (when non-zero). Pixel dimensions refer to the drawable area of the window. Opcode in the TerminalModes list is the mnemonic name, represented as a lowercase Erlang atom, defined in RFC 4254, Section 8. It can also be an Opcode if the mnemonic name is not listed in the RFC. Example: OP code: 53, mnemonic name ECHO erlang atom: echo. This event is sent as a result of calling ssh_connection:ptty_alloc/4.

Types: Shell or Command

exec_ch_msg()

(RFC 4254, section 6.5)

-type exec_ch_msg() :: {exec, ssh:channel_id(), want_reply(), Command :: string()}.

This message requests that the server starts execution of the given command. This event is sent as a result of calling ssh_connection:exec/4 .

shell_ch_msg()

(RFC 4254, section 6.5)

-type shell_ch_msg() :: {shell, ssh:channel_id(), want_reply()}.

This message requests that the user default shell is started at the other end. This event is sent as a result of calling ssh_connection:shell/2.

Types: Signals

signal_ch_msg()

(RFC 4254, section 6.9)

-type signal_ch_msg() :: {signal, ssh:channel_id(), SignalName :: string()}.

A signal can be delivered to the remote process/service using the following message. Some systems do not support signals, in which case they are to ignore this message. There is currently no function to generate this event as the signals referred to are on OS-level and not something generated by an Erlang program.

Types: Window Change

window_change_ch_msg()

(RFC 4254, section 6.7)

-type window_change_ch_msg() ::
          {window_change,
           ssh:channel_id(),
           CharWidth :: non_neg_integer(),
           RowHeight :: non_neg_integer(),
           PixelWidth :: non_neg_integer(),
           PixelHeight :: non_neg_integer()}.

When the window (terminal) size changes on the client side, it can send a message to the server side to inform it of the new dimensions. No API function generates this event.

Types

channel_id()

-type channel_id() :: ssh:channel_id().

connection_ref()

-type connection_ref() :: ssh:connection_ref().

reason()

-type reason() :: closed | timeout.

The result of a call.

If the request reached the peer, was handled and the response reached the requesting node the req_status/0 is the status reported from the peer.

If not, the reason/0 indicates what went wrong:

closed - indicates that the channel or connection was closed when trying to send the request

timeout - indicates that the operation exceeded a time limit

req_status()

-type req_status() :: success | failure.

The status of a request. Corresponds to the SSH_MSG_CHANNEL_SUCCESS and SSH_MSG_CHANNEL_FAILURE values in RFC 4254, Section 5.4.

result()

-type result() :: req_status() | {error, reason()}.

ssh_data_type_code()

-type ssh_data_type_code() :: non_neg_integer().

The valid values are 0 ("normal") and 1 ("stderr"), see RFC 4254, Section 5.2.

Functions

adjust_window(ConnectionRef, ChannelId, NumOfBytes)

-spec adjust_window(ConnectionRef, ChannelId, NumOfBytes) -> ok
                       when
                           ConnectionRef :: ssh:connection_ref(),
                           ChannelId :: ssh:channel_id(),
                           NumOfBytes :: integer().

Adjusts the SSH flow control window. This is to be done by both the client- and server-side channel processes.

Note

Channels implemented with the ssh_client_channel behavior do not normally need to call this function as flow control is handled by the behavior. The behavior adjusts the window every time the callback handle_ssh_msg/2 returns after processing channel data.

close(ConnectionRef, ChannelId)

-spec close(ConnectionRef, ChannelId) -> ok
               when ConnectionRef :: ssh:connection_ref(), ChannelId :: ssh:channel_id().

A server- or client-channel process can choose to close their session by sending a close event.

Note

This function is called by the ssh_client_channel behavior when the channel is terminated, see ssh_client_channel. Thus, channels implemented with the behavior are not to call this function explicitly.

exec(ConnectionRef, ChannelId, Command, Timeout)

-spec exec(ConnectionRef, ChannelId, Command, Timeout) -> result()
              when
                  ConnectionRef :: ssh:connection_ref(),
                  ChannelId :: ssh:channel_id(),
                  Command :: string(),
                  Timeout :: timeout().

Is to be called by a client-channel process to request that the server starts executing the given command. The result is several messages according to the following pattern. The last message is a channel close message, as the exec request is a one-time execution that closes the channel when it is done.

N x data message(s) - The result of executing the command can be only one line or thousands of lines depending on the command.

0 or 1 x eof message - Indicates that no more data is to be sent.

0 or 1 x exit signal message - Not all systems send signals. For details on valid string values, see RFC 4254, Section 6.10

0 or 1 x exit status message - It is recommended by the SSH Connection Protocol to send this message, but that is not always the case.

1 x closed status message - Indicates that the ssh_client_channel started for the execution of the command has now been shut down.

See the User's Guide section on One-Time Execution for examples.

Note

In case when command generates large amount of output data, manual window adjustment might be necessary in order to receive it. see ssh_connectino:adjust_window/3

exit_status(ConnectionRef, ChannelId, Status)

-spec exit_status(ConnectionRef, ChannelId, Status) -> ok
                     when
                         ConnectionRef :: ssh:connection_ref(),
                         ChannelId :: ssh:channel_id(),
                         Status :: integer().

Is to be called by a server-channel process to send the exit status of a command to the client.

ptty_alloc(ConnectionRef, ChannelId, Options)

(since OTP 17.5)

-spec ptty_alloc(ConnectionRef, ChannelId, Options) -> result()
                    when
                        ConnectionRef :: ssh:connection_ref(),
                        ChannelId :: ssh:channel_id(),
                        Options :: proplists:proplist().

Equivalent to ptty_alloc/4.

ptty_alloc(ConnectionRef, ChannelId, Options, Timeout)

(since OTP 17.4)

-spec ptty_alloc(ConnectionRef, ChannelId, Options, Timeout) -> result()
                    when
                        ConnectionRef :: ssh:connection_ref(),
                        ChannelId :: ssh:channel_id(),
                        Options :: proplists:proplist(),
                        Timeout :: timeout().

Sends an SSH Connection Protocol pty_req, to allocate a pseudo-terminal. Is to be called by an SSH client process.

Options:

{term, string()} - Defaults to os:getenv("TERM") or vt100 if it is undefined.

{width, integer()} - Defaults to 80 if pixel_width is not defined.

{height, integer()} - Defaults to 24 if pixel_height is not defined.

{pixel_width, integer()} - Is disregarded if width is defined.

{pixel_height, integer()} - Is disregarded if height is defined.

{pty_opts, [{posix_atom(), integer()}]} - Option can be an empty list. Otherwise, see possible POSIX names in Section 8 in RFC 4254.

reply_request(ConnectionRef, WantReply, Status, ChannelId)

-spec reply_request(ConnectionRef, WantReply, Status, ChannelId) -> ok
                       when
                           ConnectionRef :: ssh:connection_ref(),
                           WantReply :: boolean(),
                           Status :: req_status(),
                           ChannelId :: ssh:channel_id().

Sends status replies to requests where the requester has stated that it wants a status report, that is, WantReply = true. If WantReply is false, calling this function becomes a "noop". Is to be called while handling an SSH Connection Protocol message containing a WantReply boolean value.

send(ConnectionRef, ChannelId, Data)

-spec send(connection_ref(), channel_id(), iodata()) -> ok | {error, reason()}.

Equivalent to send/5.

send(ConnectionRef, ChannelId, Type, Data)

-spec send(connection_ref(), channel_id(), iodata(), timeout()) -> ok | {error, reason()};
          (connection_ref(), channel_id(), ssh_data_type_code(), iodata()) -> ok | {error, reason()}.

Depending on input arguments equivalent to one of send/5 calls specified below.

Equivalent to send(ConnectionRef, ChannelId, 0, Data, TimeOut) if called with TimeOut being integer.

Equivalent to send(ConnectionRef, ChannelId, 0, Data, infinity) if called with TimeOut being infinity atom.

Equivalent to send(ConnectionRef, ChannelId, Type, Data, infinity) if called with last argument which is not integer or infinity atom.

send(ConnectionRef, ChannelId, Type, Data, TimeOut)

-spec send(connection_ref(), channel_id(), ssh_data_type_code(), iodata(), timeout()) ->
              ok | {error, reason()}.

Is to be called by client- and server-channel processes to send data to each other.

The function subsystem/4 and subsequent calls of send/3,4,5 must be executed in the same process.

send_eof(ConnectionRef, ChannelId)

-spec send_eof(ConnectionRef, ChannelId) -> ok | {error, closed}
                  when ConnectionRef :: ssh:connection_ref(), ChannelId :: ssh:channel_id().

Sends EOF on channel ChannelId.

session_channel(ConnectionRef, Timeout)

-spec session_channel(ConnectionRef, Timeout) -> Result
                         when
                             ConnectionRef :: ssh:connection_ref(),
                             Timeout :: timeout(),
                             Result :: {ok, ssh:channel_id()} | {error, reason()}.

Equivalent to session_channel/4.

session_channel(ConnectionRef, InitialWindowSize, MaxPacketSize, Timeout)

-spec session_channel(ConnectionRef, InitialWindowSize, MaxPacketSize, Timeout) -> Result
                         when
                             ConnectionRef :: ssh:connection_ref(),
                             InitialWindowSize :: pos_integer() | undefined,
                             MaxPacketSize :: pos_integer() | undefined,
                             Timeout :: timeout(),
                             Result :: {ok, ssh:channel_id()} | {error, reason()}.

Opens a channel for an SSH session. The channel id returned from this function is the id used as input to the other functions in this module.

setenv(ConnectionRef, ChannelId, Var, Value, Timeout)

-spec setenv(ConnectionRef, ChannelId, Var, Value, Timeout) -> success
                when
                    ConnectionRef :: ssh:connection_ref(),
                    ChannelId :: ssh:channel_id(),
                    Var :: string(),
                    Value :: string(),
                    Timeout :: timeout().

Environment variables can be passed before starting the shell/command. Is to be called by a client channel processes.

shell(ConnectionRef, ChannelId)

-spec shell(ConnectionRef, ChannelId) -> Result
               when
                   ConnectionRef :: ssh:connection_ref(),
                   ChannelId :: ssh:channel_id(),
                   Result :: ok | success | failure | {error, timeout}.

Is to be called by a client channel process to request that the user default shell (typically defined in /etc/passwd in Unix systems) is executed at the server end.

Note: the return value is ok instead of success unlike in other functions in this module. This is a fault that was introduced so long ago that any change would break a large number of existing software.

subsystem(ConnectionRef, ChannelId, Subsystem, Timeout)

-spec subsystem(ConnectionRef, ChannelId, Subsystem, Timeout) -> result()
                   when
                       ConnectionRef :: ssh:connection_ref(),
                       ChannelId :: ssh:channel_id(),
                       Subsystem :: string(),
                       Timeout :: timeout().

Is to be called by a client-channel process for requesting to execute a predefined subsystem on the server.

The function subsystem/4 and subsequent calls of send/3,4,5 must be executed in the same process.

ssh_file

Default callback module for the client's and server's database operations in the ssh application

This module is the default callback handler for the client's and the server's user and host "database" operations. All data, for instance key pairs, are stored in files in the normal file system. This page documents the files, where they are stored and configuration options for this callback module.

The intention is to be compatible with the OpenSSH storage in files. Therefore it mimics directories and filenames of OpenSSH.

Ssh_file implements the ssh_server_key_api and the ssh_client_key_api. This enables the user to make an own interface using for example a database handler.

Such another callback module could be used by setting the option key_cb when starting a client or a server (with for example ssh:connect, ssh:daemon or ssh:shell ).

Callbacks

The callback functions (host_key/2, is_auth_key/3, user_key/2, is_host_key/5, add_host_key/4) are called by the SSH application internally. They are documented here to show which files and options the default implementation uses. See ssh_server_key_api and ssh_client_key_api for the callback specifications.

The public API functions are decode/2, encode/2, and extract_public_key/1.

Files, directories and who uses them

Daemons

Daemons uses all files stored in the SYSDIR directory.

Optionally, in case of publickey authorization, one or more of the remote user's public keys in the USERDIR directory are used. See the files USERDIR/authorized_keys and USERDIR/authorized_keys2.

Clients

Clients uses all files stored in the USERDIR directory.

Directory contents

LOCALUSER
The user name of the OS process running the Erlang virtual machine (emulator).

SYSDIR
This is the directory holding the server's files:

ssh_host_dsa_key - private dss host key (optional)

ssh_host_rsa_key - private rsa host key (optional)

ssh_host_ecdsa_key - private ecdsa host key (optional)

ssh_host_ed25519_key - private eddsa host key for curve 25519 (optional)

ssh_host_ed448_key - private eddsa host key for curve 448 (optional)

The key files could be generated with OpenSSH's ssh-keygen command.

At least one host key must be defined. The default value of SYSDIR is /etc/ssh.

For security reasons, this directory is normally accessible only to the root user.

To change the SYSDIR, see the system_dir option.

USERDIR
This is the directory holding the files:

authorized_keys and, as second alternative authorized_keys2 - the user's public keys are stored concatenated in one of those files.

It is composed of lines as for OpenSSH:

(options)? keytype base64-encoded-key comment

where

options :: option(,option)*
option :: % All options are skipped
keytype :: 'ssh-dsa'
         | 'ssh-rsa'
         | 'ssh-ecdsa-nistp256'
     | 'ssh-ecdsa-nistp384'
         | 'ssh-ecdsa-nistp521'
         | 'ssh-ed25519'
     | 'ssh-ed448'
base64-encoded-key :: % The user's public key
comment :: % Comments are skipped

known_hosts - host keys from hosts visited concatenated. The file is created and used by the client.

It is composed of lines as for OpenSSH:

(option)? pattern(,pattern)* keytype key (comment)?

where

option :: '@revoked'
pattern :: host | '[' host ']:' port
host :: ip-address | hostname | '*'
port :: portnumber | '*'
keytype :: 'ssh-dsa'
         | 'ssh-rsa'
         | 'ssh-ecdsa-nistp256'
     | 'ssh-ecdsa-nistp384'
         | 'ssh-ecdsa-nistp521'
         | 'ssh-ed25519'
     | 'ssh-ed448'
key :: % encoded key from eg ssh_host_*.pub

id_dsa - private dss user key (optional)

id_rsa - private rsa user key (optional)

id_ecdsa - private ecdsa user key (optional)

id_ed25519 - private eddsa user key for curve 25519 (optional)

id_ed448 - private eddsa user key for curve 448 (optional)

The key files could be generated with OpenSSH's ssh-keygen command.

The default value of USERDIR is /home/LOCALUSER/.ssh.

To change the USERDIR, see the user_dir option

Summary

Types: Options

experimental_openssh_key_v1_decode()

experimental_openssh_key_v1_encode()

key()

The key representation

openssh_key_v1_attributes()

Types for the experimental implementation of the openssh_key_v1 format.

optimize_key_lookup()

Make the handling of large files fast by setting time, but this will use more memory. The space variant shrinks the memory requirements, but with a higher time consumption.

pubkey_passphrase_client_options()

If the user's DSA, RSA or ECDSA key is protected by a passphrase, it can be supplied with those options.

system_dir_daemon_option()

Sets the system directory.

user2dir()

Sets the user directory dynamically by evaluating the user2dir function.

user_dir_common_option()

Sets the user directory.

user_dir_fun_common_option()

API

decode(SshBin, Type)

Decodes an SSH file-binary.

encode(InData, Type)

Encodes a list of SSH file entries (public keys and attributes) to a binary.

extract_public_key(PrivKey)

Fetches the public key from a private key.

Callback Implementations

add_host_key(Host, Port, Key, Options)

Implements ssh_client_key_api:add_host_key/4.

host_key(Algorithm, Options)

Implements ssh_server_key_api:host_key/2.

is_auth_key(Key, User, Options)

Implements ssh_server_key_api:is_auth_key/3.

is_host_key(Key, Host, Port, Algorithm, Options)

Implements ssh_client_key_api:is_host_key/5.

user_key(Algorithm, Options)

Implements ssh_client_key_api:user_key/2.

Types: Options

experimental_openssh_key_v1_decode()

(since OTP 21.2)

-type experimental_openssh_key_v1_decode() :: [{key(), openssh_key_v1_attributes()}].

experimental_openssh_key_v1_encode()

(since OTP 21.2)

-type experimental_openssh_key_v1_encode() ::
          [{[{public_key:public_key(), public_key:private_key(), Comment :: binary()} |
             {public_key:private_key(), Comment :: binary()}],
            openssh_key_v1_attributes()}].

key()

(since OTP 21.2)

-type key() :: public_key:public_key() | public_key:private_key().

The key representation

openssh_key_v1_attributes()

(since OTP 21.2)

-type openssh_key_v1_attributes() :: [{atom(), term()}].

Types for the experimental implementation of the openssh_key_v1 format.

optimize_key_lookup()

(since OTP 21.2)

-type optimize_key_lookup() :: {optimize, time | space}.

Make the handling of large files fast by setting time, but this will use more memory. The space variant shrinks the memory requirements, but with a higher time consumption.

To set it, set the option {key_cb, {ssh_file, [{optimize,TimeOrSpace}]} in the call of ssh:connect/3, ssh:daemon/2 or similar function call that initiates an ssh connection.

pubkey_passphrase_client_options()

(since OTP 21.2)

-type pubkey_passphrase_client_options() ::
          {dsa_pass_phrase, string()} | {rsa_pass_phrase, string()} | {ecdsa_pass_phrase, string()}.

If the user's DSA, RSA or ECDSA key is protected by a passphrase, it can be supplied with those options.

Note that EdDSA passhrases (Curves 25519 and 448) are not implemented.

system_dir_daemon_option()

(since OTP 21.2)

-type system_dir_daemon_option() :: {system_dir, string()}.

Sets the system directory.

user2dir()

(since OTP 21.2)

-type user2dir() :: fun((RemoteUserName :: string()) -> UserDir :: string()).

Sets the user directory dynamically by evaluating the user2dir function.

user_dir_common_option()

(since OTP 21.2)

-type user_dir_common_option() :: {user_dir, string()}.

Sets the user directory.

user_dir_fun_common_option()

(since OTP 21.2)

-type user_dir_fun_common_option() :: {user_dir_fun, user2dir()}.

API

decode(SshBin, Type)

(since OTP 24.0)

-spec decode(SshBin, Type) -> Decoded | {error, term()}
                when
                    SshBin :: binary(),
                    Type ::
                        ssh2_pubkey | public_key | openssh_key | rfc4716_key | openssh_key_v1 |
                        known_hosts | auth_keys,
                    Decoded ::
                        Decoded_ssh2_pubkey | Decoded_public | Decoded_openssh | Decoded_rfc4716 |
                        Decoded_openssh_key_v1 | Decoded_known_hosts | Decoded_auth_keys,
                    Decoded_ssh2_pubkey :: public_key:public_key(),
                    Decoded_public :: Decoded_rfc4716 | Decoded_openssh_key_v1 | Decoded_openssh,
                    Decoded_openssh :: [{public_key:public_key(), [{comment, string()}]}],
                    Decoded_rfc4716 :: [{key(), [{headers, Attrs}]}],
                    Decoded_openssh_key_v1 :: experimental_openssh_key_v1_decode(),
                    Decoded_known_hosts ::
                        [{public_key:public_key(), [{comment, string()} | {hostnames, [string()]}]}],
                    Decoded_auth_keys ::
                        [{public_key:public_key(), [{comment, string()} | {options, [string()]}]}],
                    Attrs :: {Key :: string(), Value :: string()}.

Decodes an SSH file-binary.

If Type is public_key the binary can be either an RFC4716 public key or an OpenSSH public key.

Note

The implementation of the openssh_key_v1 format is still experimental.

encode(InData, Type)

(since OTP 24.0)

-spec encode(InData, Type) -> binary() | {error, term()}
                when
                    Type ::
                        ssh2_pubkey | openssh_key | rfc4716_key | openssh_key_v1 | known_hosts |
                        auth_keys,
                    InData ::
                        InData_ssh2_pubkey | InData_openssh | InData_rfc4716 | InData_openssh_key_v1 |
                        InData_known_hosts | InData_auth_keys,
                    InData_ssh2_pubkey :: public_key:public_key(),
                    InData_openssh :: [{public_key:public_key(), [{comment, string()}]}],
                    InData_rfc4716 :: [{key(), [{headers, Attrs}]}],
                    InData_openssh_key_v1 :: experimental_openssh_key_v1_encode(),
                    InData_known_hosts ::
                        [{public_key:public_key(), [{comment, string()} | {hostnames, [string()]}]}],
                    InData_auth_keys ::
                        [{public_key:public_key(), [{comment, string()} | {options, [string()]}]}],
                    Attrs :: {Key :: string(), Value :: string()}.

Encodes a list of SSH file entries (public keys and attributes) to a binary.

Note

The implementation of the openssh_key_v1 format is still experimental.

extract_public_key(PrivKey)

(since OTP 25.0)

-spec extract_public_key(PrivKey) -> PubKey
                            when PrivKey :: public_key:private_key(), PubKey :: public_key:public_key().

Fetches the public key from a private key.

Callback Implementations

add_host_key(Host, Port, Key, Options)

(since OTP 23.0)

-spec add_host_key(Host, Port, Key, Options) -> Result
                      when
                          Host ::
                              inet:ip_address() |
                              inet:hostname() |
                              [inet:ip_address() | inet:hostname()],
                          Port :: inet:port_number(),
                          Key :: public_key:public_key(),
                          Options :: ssh_client_key_api:client_key_cb_options(none()),
                          Result :: ok | {error, term()}.

Implements ssh_client_key_api:add_host_key/4.

Option

user_dir

File

USERDIR/known_hosts

host_key(Algorithm, Options)

(since OTP 21.2)

-spec host_key(Algorithm, Options) -> Result
                  when
                      Algorithm :: ssh:pubkey_alg(),
                      Result :: {ok, public_key:private_key()} | {error, term()},
                      Options :: ssh_server_key_api:daemon_key_cb_options(none()).

Implements ssh_server_key_api:host_key/2.

Options

system_dir

Files

SYSDIR/ssh_host_rsa_key

SYSDIR/ssh_host_dsa_key

SYSDIR/ssh_host_ecdsa_key

SYSDIR/ssh_host_ed25519_key

SYSDIR/ssh_host_ed448_key

is_auth_key(Key, User, Options)

(since OTP 21.2)

-spec is_auth_key(Key, User, Options) -> boolean()
                     when
                         Key :: public_key:public_key(),
                         User :: string(),
                         Options :: ssh_server_key_api:daemon_key_cb_options(optimize_key_lookup()).

Implements ssh_server_key_api:is_auth_key/3.

Options

user_dir_fun

user_dir

Files

USERDIR/authorized_keys

USERDIR/authorized_keys2

This functions discards all options in the beginning of the lines of thoose files when reading them.

is_host_key(Key, Host, Port, Algorithm, Options)

(since OTP 23.0)

-spec is_host_key(Key, Host, Port, Algorithm, Options) -> Result
                     when
                         Key :: public_key:public_key(),
                         Host ::
                             inet:ip_address() | inet:hostname() | [inet:ip_address() | inet:hostname()],
                         Port :: inet:port_number(),
                         Algorithm :: ssh:pubkey_alg(),
                         Options :: ssh_client_key_api:client_key_cb_options(optimize_key_lookup()),
                         Result :: boolean() | {error, term()}.

Implements ssh_client_key_api:is_host_key/5.

Option

user_dir

File

USERDIR/known_hosts

user_key(Algorithm, Options)

(since OTP 21.2)

-spec user_key(Algorithm, Options) -> Result
                  when
                      Algorithm :: ssh:pubkey_alg(),
                      Result :: {ok, public_key:private_key()} | {error, string()},
                      Options :: ssh_client_key_api:client_key_cb_options(none()).

Implements ssh_client_key_api:user_key/2.

Options

user_dir

dsa_pass_phrase

rsa_pass_phrase

ecdsa_pass_phrase

Note that EdDSA passhrases (Curves 25519 and 448) are not implemented.

Files

USERDIR/id_dsa

USERDIR/id_rsa

USERDIR/id_ecdsa

USERDIR/id_ed25519

USERDIR/id_ed448

ssh_server_channel behaviour

-behaviour(ssh_server_channel). (Replaces ssh_daemon_channel)

Note

This module replaces ssh_daemon_channel.

The old module is still available for compatibility, but should not be used for new programs. The old module will not be maintained except for some error corrections

SSH services (clients and servers) are implemented as channels that are multiplexed over an SSH connection and communicates over the SSH Connection Protocol. This module provides a callback API that takes care of generic channel aspects for daemons, such as flow control and close messages. It lets the callback functions take care of the service (application) specific parts. This behavior also ensures that the channel process honors the principal of an OTP-process so that it can be part of a supervisor tree. This is a requirement of channel processes implementing a subsystem that will be added to the ssh applications supervisor tree.

Note

When implementing a client subsystem handler, use -behaviour(ssh_client_channel) instead.

Summary

Callbacks

handle_msg(Msg, State)

Handles other messages than SSH Connection Protocol, call, or cast messages sent to the channel.

handle_ssh_msg/2

Handles SSH Connection Protocol messages that may need service-specific attention. For details, see ssh_connection:event/0.

init(Args)

Makes necessary initializations and returns the initial channel state if the initializations succeed.

terminate(Reason, State)

This function is called by a channel process when it is about to terminate. Before this function is called, ssh_connection:close/2 is called, if it has not been called earlier. This function does any necessary cleaning up. When it returns, the channel process terminates with reason Reason. The return value is ignored.

Callbacks

handle_msg(Msg, State)

(since OTP 21.0)

-callback handle_msg(Msg :: term(), State :: term()) ->
                        {ok, State :: term()} | {stop, ChannelId :: ssh:channel_id(), State :: term()}.

Handles other messages than SSH Connection Protocol, call, or cast messages sent to the channel.

Possible Erlang 'EXIT' messages is to be handled by this function and all channels are to handle the following message.

{ssh_channel_up, ssh:channel_id/0 , ssh:connection_ref/0 } - This is the first message that the channel receives. This is especially useful if the server wants to send a message to the client without first receiving a message from it. If the message is not useful for your particular scenario, ignore it by immediately returning {ok, State}.

handle_ssh_msg/2

(since OTP 21.0)

-callback handle_ssh_msg(ssh_connection:event(), State :: term()) ->
                            {ok, State :: term()} | {stop, ChannelId :: ssh:channel_id(), State :: term()}.

Handles SSH Connection Protocol messages that may need service-specific attention. For details, see ssh_connection:event/0.

The following message is taken care of by the ssh_server_channel behavior.

{closed, ssh:channel_id/0 } - The channel behavior sends a close message to the other side, if such a message has not already been sent. Then it terminates the channel with reason normal.

init(Args)

(since OTP 21.0)

-callback init(Args :: term()) ->
                  {ok, State :: term()} |
                  {ok, State :: term(), timeout() | hibernate} |
                  {stop, Reason :: term()} |
                  ignore.

Makes necessary initializations and returns the initial channel state if the initializations succeed.

The time-out values that can be returned have the same semantics as in a gen_server. If the time-out occurs, handle_msg/2 is called as handle_msg(timeout, State).

terminate(Reason, State)

(since OTP 21.0)

-callback terminate(Reason :: normal | shutdown | {shutdown, term()} | term(), State :: term()) -> term().

This function is called by a channel process when it is about to terminate. Before this function is called, ssh_connection:close/2 is called, if it has not been called earlier. This function does any necessary cleaning up. When it returns, the channel process terminates with reason Reason. The return value is ignored.

ssh_server_key_api behaviour

-behaviour(ssh_server_key_api).

Behaviour describing the API for public key handling of an SSH server. By implementing the callbacks defined in this behavior, the public key handling of an SSH server can be customized. By default the SSH application implements this behavior with help of the standard OpenSSH files, see the ssh application manual.

Summary

Types

daemon_key_cb_options(T)

Options provided to ssh:daemon/2,3.

Callbacks

host_key(Algorithm, DaemonOptions)

Fetches the private key of the host.

is_auth_key(PublicKey, User, DaemonOptions)

Checks if the user key is authorized.

Types

daemon_key_cb_options(T)

(since OTP R16B)

-type daemon_key_cb_options(T) :: [{key_cb_private, [T]} | ssh:daemon_option()].

Options provided to ssh:daemon/2,3.

The option list given in the key_cb option is available with the key key_cb_private.

Callbacks

host_key(Algorithm, DaemonOptions)

(since OTP R16B)

-callback host_key(Algorithm :: ssh:pubkey_alg(), DaemonOptions :: daemon_key_cb_options(any())) ->
                      {ok, PrivateKey :: public_key:private_key()} | {error, term()}.

Fetches the private key of the host.

is_auth_key(PublicKey, User, DaemonOptions)

(since OTP R16B)

-callback is_auth_key(PublicKey :: public_key:public_key(),
                      User :: string(),
                      DaemonOptions :: daemon_key_cb_options(any())) ->
                         boolean().

Checks if the user key is authorized.

ssh_sftp

SFTP client.

This module implements an SSH FTP (SFTP) client. SFTP is a secure, encrypted file transfer service available for SSH.

Summary

Types: Crypto open_tar

chunk_size()

crypto_fun()

crypto_result()

The initial crypto_state/0 returned from the init_fun/0 is folded into repeated applications of the crypto_fun/0 in the tar_crypto_spec. The binary returned from that fun is sent to the remote SFTP server and the new crypto_state/0 is used in the next call of the crypto_fun/0.

crypto_state()

The init_fun/0 in the tar_crypto_spec is applied once prior to any other crypto operation. The intention is that this function initiates the encryption or decryption for example by calling crypto:crypto_init/4 or similar. The crypto_state/0 is the state such a function may return.

decrypt_spec()

Specifies the encryption or decryption applied to tar files when using open_tar/3 or open_tar/4.

encrypt_spec()

final_fun()

If doing encryption, the final_fun/0 in the tar_crypto_spec is applied to the last piece of data. The final_fun/0 is responsible for padding (if needed) and encryption of that last piece.

init_fun()

tar_crypto_spec()

Types

reason()

A description of the reason why an operation failed.

sftp_option()

Specifies available SFTP options.

Functions

apread(ChannelPid, Handle, Position, Len)

The apread/4 function reads from a specified position, combining the position/3 and aread/3 functions.

apwrite(ChannelPid, Handle, Position, Data)

The apwrite/4 function writes to a specified position, combining the position/3 and awrite/3 functions.

aread(ChannelPid, Handle, Len)

Reads from an open file, without waiting for the result. If the handle is valid, the function returns {async, N}, where N is a term guaranteed to be unique between calls of aread. The actual data is sent as a message to the calling process. This message has the form {async_reply, N, Result}, where Result is the result from the read, either {ok, Data}, eof, or {error, reason()}.

awrite(ChannelPid, Handle, Data)

Writes to an open file, without waiting for the result. If the handle is valid, the function returns {async, N}, where N is a term guaranteed to be unique between calls of awrite. The result of the write operation is sent as a message to the calling process. This message has the form {async_reply, N, Result}, where Result is the result from the write, either ok, or {error, reason()}.

close(ChannelPid, Handle)

Equivalent to close/3.

close(ChannelPid, Handle, Timeout)

Closes a handle to an open file or directory on the server.

del_dir(ChannelPid, Name)

Equivalent to del_dir/3.

del_dir(ChannelPid, Name, Timeout)

Deletes a directory specified by Name. The directory must be empty before it can be successfully deleted.

delete(ChannelPid, Name)

Equivalent to delete/3.

delete(ChannelPid, Name, Timeout)

Deletes the file specified by Name.

list_dir(ChannelPid, Path)

Equivalent to list_dir/3.

list_dir(ChannelPid, Path, Timeout)

Lists the given directory on the server, returning the filenames as a list of strings.

make_dir(ChannelPid, Name)

Equivalent to make_dir/3.

make_dir(ChannelPid, Name, Timeout)

Creates a directory specified by Name. Name must be a full path to a new directory. The directory can only be created in an existing directory.

make_symlink(ChannelPid, Name, Target)

Equivalent to make_symlink/4.

make_symlink(ChannelPid, Name, Target, Timeout)

Creates a symbolic link pointing to Target with the name Name.

open(ChannelPid, Name, Mode)

Equivalent to open/4.

open(ChannelPid, Name, Mode, Timeout)

Opens a file on the server and returns a handle, which can be used for reading or writing.

open_tar(ChannelPid, Path, Mode)

Equivalent to open_tar/4.

open_tar(ChannelPid, Path, Mode, Timeout)

Opens a handle to a tar file on the server, associated with ChannelPid. The handle can be used for remote tar creation and extraction. The actual writing and reading is performed by calls to erl_tar:add/3,4 and erl_tar:extract/2. Note: The erl_tar:init/3 function should not be called, that one is called by this open_tar function.

opendir(ChannelPid, Path)

Equivalent to opendir/3.

opendir(ChannelPid, Path, Timeout)

Opens a handle to a directory on the server. The handle can be used for reading directory contents.

position(ChannelPid, Handle, Location)

Equivalent to position/4.

position(ChannelPid, Handle, Location, Timeout)

Sets the file position of the file referenced by Handle. Returns {ok, NewPosition} (as an absolute offset) if successful, otherwise {error, reason()}. Location is one of the following

pread(ChannelPid, Handle, Position, Len)

Equivalent to pread/5.

pread(ChannelPid, Handle, Position, Len, Timeout)

The pread/3,4 function reads from a specified position, combining the position/3 and read/3,4 functions.

pwrite(ChannelPid, Handle, Position, Data)

Equivalent to pwrite/5.

pwrite(ChannelPid, Handle, Position, Data, Timeout)

The pwrite/3,4 function writes to a specified position, combining the position/3 and write/3,4 functions.

read(ChannelPid, Handle, Len)

Equivalent to read/4.

read(ChannelPid, Handle, Len, Timeout)

Reads Len bytes from the file referenced by Handle. Returns {ok, Data}, eof, or {error, reason()}. If the file is opened with binary, Data is a binary, otherwise it is a string.

read_file(ChannelPid, File)

Equivalent to read_file/3.

read_file(ChannelPid, File, Timeout)

Reads a file from the server, and returns the data in a binary.

read_file_info(ChannelPid, Name)

Equivalent to read_file_info/3.

read_file_info(ChannelPid, Name, Timeout)

Returns a file_info record from the file system object specified by Name or Handle. See file:read_file_info/2 for information about the record.

read_link(ChannelPid, Name)

Equivalent to read_link/3.

read_link(ChannelPid, Name, Timeout)

Reads the link target from the symbolic link specified by name.

read_link_info(ChannelPid, Name)

Equivalent to read_link_info/3.

read_link_info(ChannelPid, Name, Timeout)

Returns a file_info record from the symbolic link specified by Name or Handle. See file:read_link_info/2 for information about the record.

rename(ChannelPid, OldName, NewName)

Equivalent to rename/4.

rename(ChannelPid, OldName, NewName, Timeout)

Renames a file named OldName and gives it the name NewName.

start_channel(Dest)

Equivalent to start_channel/2.

start_channel/2

Starts new ssh channel for communicating with the SFTP server.

start_channel(Host, Port, UserOptions0)

Starts new ssh connection and channel for communicating with the SFTP server.

stop_channel(ChannelPid)

Stops an SFTP channel. Does not close the SSH connection. Use ssh:close/1 to close it.

write(ChannelPid, Handle, Data)

Equivalent to write/4.

write(ChannelPid, Handle, Data, Timeout)

Writes data to the file referenced by Handle. The file is to be opened with write or append flag. Returns ok if successful or {error, reason()} otherwise.

write_file(ChannelPid, File, Data)

Equivalent to write_file/4.

write_file(ChannelPid, File, Data, Timeout)

Writes a file to the server. The file is created if it does not exist but overwritten if it exists.

write_file_info(ChannelPid, Name, FileInfo)

Equivalent to write_file_info/4.

write_file_info(ChannelPid, Name, FileInfo, Timeout)

Writes file information from a file_info record to the file specified by Name. See file:write_file_info/2,3 for information about the record.

Types: Crypto open_tar

chunk_size()

-type chunk_size() :: undefined | pos_integer().

crypto_fun()

-type crypto_fun() :: fun((TextIn :: binary(), crypto_state()) -> crypto_result()).

crypto_result()

-type crypto_result() ::
          {ok, TextOut :: binary(), crypto_state()} |
          {ok, TextOut :: binary(), crypto_state(), chunk_size()}.

The initial crypto_state/0 returned from the init_fun/0 is folded into repeated applications of the crypto_fun/0 in the tar_crypto_spec. The binary returned from that fun is sent to the remote SFTP server and the new crypto_state/0 is used in the next call of the crypto_fun/0.

If the crypto_fun/0 reurns a chunk_size/0, that value is as block size for further blocks in calls to crypto_fun/0.

crypto_state()

-type crypto_state() :: any().

The init_fun/0 in the tar_crypto_spec is applied once prior to any other crypto operation. The intention is that this function initiates the encryption or decryption for example by calling crypto:crypto_init/4 or similar. The crypto_state/0 is the state such a function may return.

If the selected cipher needs to have the input data partitioned into blocks of a certain size, the init_fun/0 should return the second form of return value with the chunk_size/0 set to the block size. If the chunk_size/0 is undefined, the size of the PlainBins varies, because this is intended for stream crypto, whereas a fixed chunk_size/0 is intended for block crypto. A chunk_size/0 can be changed in the return from the crypto_fun/0. The value can be changed between pos_integer/0 and undefined.

decrypt_spec()

-type decrypt_spec() :: {init_fun(), crypto_fun()}.

Specifies the encryption or decryption applied to tar files when using open_tar/3 or open_tar/4.

The encryption or decryption is applied to the generated stream of bytes prior to sending the resulting stream to the SFTP server.

For code examples see Section Example with encryption in the ssh Users Guide.

encrypt_spec()

-type encrypt_spec() :: {init_fun(), crypto_fun(), final_fun()}.

final_fun()

-type final_fun() :: fun((FinalTextIn :: binary(), crypto_state()) -> {ok, FinalTextOut :: binary()}).

If doing encryption, the final_fun/0 in the tar_crypto_spec is applied to the last piece of data. The final_fun/0 is responsible for padding (if needed) and encryption of that last piece.

init_fun()

-type init_fun() :: fun(() -> {ok, crypto_state()}) | fun(() -> {ok, crypto_state(), chunk_size()}).

tar_crypto_spec()

-type tar_crypto_spec() :: encrypt_spec() | decrypt_spec().

Types

reason()

-type reason() :: atom() | string() | tuple().

A description of the reason why an operation failed.

The atom/0 value is formed from the sftp error codes in the protocol-level responses as defined in draft-ietf-secsh-filexfer-13 section 9.1. The codes are named as SSH_FX_* which are transformed into lowercase of the star-part. E.g. the error code SSH_FX_NO_SUCH_FILE will cause the reason/0 to be no_such_file.

The string/0 reason is the error information from the server in case of an exit-signal. If that information is empty, the reason is the exit signal name.

The tuple/0 reason are other errors like for example {exit_status,1}.

sftp_option()

-type sftp_option() ::
          {timeout, timeout()} |
          {sftp_vsn, pos_integer()} |
          {window_size, pos_integer()} |
          {packet_size, pos_integer()}.

Specifies available SFTP options.

Functions

apread(ChannelPid, Handle, Position, Len)

-spec apread(ChannelPid, Handle, Position, Len) -> {async, N} | Error
                when
                    ChannelPid :: pid(),
                    Handle :: term(),
                    Position :: integer(),
                    Len :: integer(),
                    Error :: {error, reason()},
                    N :: term().

The apread/4 function reads from a specified position, combining the position/3 and aread/3 functions.

apwrite(ChannelPid, Handle, Position, Data)

-spec apwrite(ChannelPid, Handle, Position, Data) -> {async, N} | Error
                 when
                     ChannelPid :: pid(),
                     Handle :: term(),
                     Position :: integer(),
                     Data :: binary(),
                     Error :: {error, reason()},
                     N :: term().

The apwrite/4 function writes to a specified position, combining the position/3 and awrite/3 functions.

aread(ChannelPid, Handle, Len)

-spec aread(ChannelPid, Handle, Len) -> {async, N} | Error
               when
                   ChannelPid :: pid(),
                   Handle :: term(),
                   Len :: integer(),
                   Error :: {error, reason()},
                   N :: term().

Reads from an open file, without waiting for the result. If the handle is valid, the function returns {async, N}, where N is a term guaranteed to be unique between calls of aread. The actual data is sent as a message to the calling process. This message has the form {async_reply, N, Result}, where Result is the result from the read, either {ok, Data}, eof, or {error, reason()}.

awrite(ChannelPid, Handle, Data)

-spec awrite(ChannelPid, Handle, Data) -> {async, N} | Error
                when
                    ChannelPid :: pid(),
                    Handle :: term(),
                    Data :: binary(),
                    Error :: {error, reason()},
                    N :: term().

Writes to an open file, without waiting for the result. If the handle is valid, the function returns {async, N}, where N is a term guaranteed to be unique between calls of awrite. The result of the write operation is sent as a message to the calling process. This message has the form {async_reply, N, Result}, where Result is the result from the write, either ok, or {error, reason()}.

close(ChannelPid, Handle)

-spec close(ChannelPid, Handle) -> ok | Error
               when ChannelPid :: pid(), Handle :: term(), Error :: {error, reason()}.

Equivalent to close/3.

close(ChannelPid, Handle, Timeout)

-spec close(ChannelPid, Handle, Timeout) -> ok | Error
               when
                   ChannelPid :: pid(),
                   Handle :: term(),
                   Timeout :: timeout(),
                   Error :: {error, reason()}.

Closes a handle to an open file or directory on the server.

del_dir(ChannelPid, Name)

-spec del_dir(ChannelPid, Name) -> ok | Error
                 when ChannelPid :: pid(), Name :: string(), Error :: {error, reason()}.

Equivalent to del_dir/3.

del_dir(ChannelPid, Name, Timeout)

-spec del_dir(ChannelPid, Name, Timeout) -> ok | Error
                 when
                     ChannelPid :: pid(),
                     Name :: string(),
                     Timeout :: timeout(),
                     Error :: {error, reason()}.

Deletes a directory specified by Name. The directory must be empty before it can be successfully deleted.

delete(ChannelPid, Name)

-spec delete(ChannelPid, Name) -> ok | Error
                when ChannelPid :: pid(), Name :: string(), Error :: {error, reason()}.

Equivalent to delete/3.

delete(ChannelPid, Name, Timeout)

-spec delete(ChannelPid, Name, Timeout) -> ok | Error
                when
                    ChannelPid :: pid(),
                    Name :: string(),
                    Timeout :: timeout(),
                    Error :: {error, reason()}.

Deletes the file specified by Name.

list_dir(ChannelPid, Path)

-spec list_dir(ChannelPid, Path) -> {ok, FileNames} | Error
                  when
                      ChannelPid :: pid(),
                      Path :: string(),
                      FileNames :: [FileName],
                      FileName :: string(),
                      Error :: {error, reason()}.

Equivalent to list_dir/3.

list_dir(ChannelPid, Path, Timeout)

-spec list_dir(ChannelPid, Path, Timeout) -> {ok, FileNames} | Error
                  when
                      ChannelPid :: pid(),
                      Path :: string(),
                      Timeout :: timeout(),
                      FileNames :: [FileName],
                      FileName :: string(),
                      Error :: {error, reason()}.

Lists the given directory on the server, returning the filenames as a list of strings.

make_dir(ChannelPid, Name)

-spec make_dir(ChannelPid, Name) -> ok | Error
                  when ChannelPid :: pid(), Name :: string(), Error :: {error, reason()}.

Equivalent to make_dir/3.

make_dir(ChannelPid, Name, Timeout)

-spec make_dir(ChannelPid, Name, Timeout) -> ok | Error
                  when
                      ChannelPid :: pid(),
                      Name :: string(),
                      Timeout :: timeout(),
                      Error :: {error, reason()}.

Creates a directory specified by Name. Name must be a full path to a new directory. The directory can only be created in an existing directory.

make_symlink(ChannelPid, Name, Target)

-spec make_symlink(ChannelPid, Name, Target) -> ok | Error
                      when
                          ChannelPid :: pid(),
                          Name :: string(),
                          Target :: string(),
                          Error :: {error, reason()}.

Equivalent to make_symlink/4.

make_symlink(ChannelPid, Name, Target, Timeout)

-spec make_symlink(ChannelPid, Name, Target, Timeout) -> ok | Error
                      when
                          ChannelPid :: pid(),
                          Name :: string(),
                          Target :: string(),
                          Timeout :: timeout(),
                          Error :: {error, reason()}.

Creates a symbolic link pointing to Target with the name Name.

open(ChannelPid, Name, Mode)

-spec open(ChannelPid, Name, Mode) -> {ok, Handle} | Error
              when
                  ChannelPid :: pid(),
                  Name :: string(),
                  Mode :: [read | write | append | binary | raw],
                  Handle :: term(),
                  Error :: {error, reason()}.

Equivalent to open/4.

open(ChannelPid, Name, Mode, Timeout)

-spec open(ChannelPid, Name, Mode, Timeout) -> {ok, Handle} | Error
              when
                  ChannelPid :: pid(),
                  Name :: string(),
                  Mode :: [read | write | append | binary | raw],
                  Timeout :: timeout(),
                  Handle :: term(),
                  Error :: {error, reason()}.

Opens a file on the server and returns a handle, which can be used for reading or writing.

open_tar(ChannelPid, Path, Mode)

(since OTP 17.4)

-spec open_tar(ChannelPid, Path, Mode) -> {ok, Handle} | Error
                  when
                      ChannelPid :: pid(),
                      Path :: string(),
                      Mode :: [read | write | {crypto, tar_crypto_spec()}],
                      Handle :: term(),
                      Error :: {error, reason()}.

Equivalent to open_tar/4.

open_tar(ChannelPid, Path, Mode, Timeout)

(since OTP 17.4)

-spec open_tar(ChannelPid, Path, Mode, Timeout) -> {ok, Handle} | Error
                  when
                      ChannelPid :: pid(),
                      Path :: string(),
                      Mode :: [read | write | {crypto, tar_crypto_spec()}],
                      Timeout :: timeout(),
                      Handle :: term(),
                      Error :: {error, reason()}.

Opens a handle to a tar file on the server, associated with ChannelPid. The handle can be used for remote tar creation and extraction. The actual writing and reading is performed by calls to erl_tar:add/3,4 and erl_tar:extract/2. Note: The erl_tar:init/3 function should not be called, that one is called by this open_tar function.

For code examples see Section SFTP Client with TAR Compression in the ssh Users Guide.

The crypto mode option is explained in the data types section above, see Crypto operations for open_tar. Encryption is assumed if the Mode contains write, and decryption if the Mode contains read.

opendir(ChannelPid, Path)

-spec opendir(ChannelPid, Path) -> {ok, Handle} | Error
                 when
                     ChannelPid :: pid(), Path :: string(), Handle :: term(), Error :: {error, reason()}.

Equivalent to opendir/3.

opendir(ChannelPid, Path, Timeout)

-spec opendir(ChannelPid, Path, Timeout) -> {ok, Handle} | Error
                 when
                     ChannelPid :: pid(),
                     Path :: string(),
                     Timeout :: timeout(),
                     Handle :: term(),
                     Error :: {error, reason()}.

Opens a handle to a directory on the server. The handle can be used for reading directory contents.

position(ChannelPid, Handle, Location)

-spec position(ChannelPid, Handle, Location) -> {ok, NewPosition} | Error
                  when
                      ChannelPid :: pid(),
                      Handle :: term(),
                      Location ::
                          Offset | {bof, Offset} | {cur, Offset} | {eof, Offset} | bof | cur | eof,
                      Offset :: integer(),
                      NewPosition :: integer(),
                      Error :: {error, reason()}.

Equivalent to position/4.

position(ChannelPid, Handle, Location, Timeout)

-spec position(ChannelPid, Handle, Location, Timeout) -> {ok, NewPosition} | Error
                  when
                      ChannelPid :: pid(),
                      Handle :: term(),
                      Location ::
                          Offset | {bof, Offset} | {cur, Offset} | {eof, Offset} | bof | cur | eof,
                      Timeout :: timeout(),
                      Offset :: integer(),
                      NewPosition :: integer(),
                      Error :: {error, reason()}.

Sets the file position of the file referenced by Handle. Returns {ok, NewPosition} (as an absolute offset) if successful, otherwise {error, reason()}. Location is one of the following:

Offset - The same as {bof, Offset}.

{bof, Offset} - Absolute offset.

{cur, Offset} - Offset from the current position.

{eof, Offset} - Offset from the end of file.

bof | cur | eof - The same as eariler with Offset 0, that is, {bof, 0} | {cur, 0} | {eof, 0}.

pread(ChannelPid, Handle, Position, Len)

-spec pread(ChannelPid, Handle, Position, Len) -> {ok, Data} | eof | Error
               when
                   ChannelPid :: pid(),
                   Handle :: term(),
                   Position :: integer(),
                   Len :: integer(),
                   Data :: string() | binary(),
                   Error :: {error, reason()}.

Equivalent to pread/5.

pread(ChannelPid, Handle, Position, Len, Timeout)

-spec pread(ChannelPid, Handle, Position, Len, Timeout) -> {ok, Data} | eof | Error
               when
                   ChannelPid :: pid(),
                   Handle :: term(),
                   Position :: integer(),
                   Len :: integer(),
                   Timeout :: timeout(),
                   Data :: string() | binary(),
                   Error :: {error, reason()}.

The pread/3,4 function reads from a specified position, combining the position/3 and read/3,4 functions.

pwrite(ChannelPid, Handle, Position, Data)

-spec pwrite(ChannelPid, Handle, Position, Data) -> ok | Error
                when
                    ChannelPid :: pid(),
                    Handle :: term(),
                    Position :: integer(),
                    Data :: iolist(),
                    Error :: {error, reason()}.

Equivalent to pwrite/5.

pwrite(ChannelPid, Handle, Position, Data, Timeout)

-spec pwrite(ChannelPid, Handle, Position, Data, Timeout) -> ok | Error
                when
                    ChannelPid :: pid(),
                    Handle :: term(),
                    Position :: integer(),
                    Data :: iolist(),
                    Timeout :: timeout(),
                    Error :: {error, reason()}.

The pwrite/3,4 function writes to a specified position, combining the position/3 and write/3,4 functions.

read(ChannelPid, Handle, Len)

-spec read(ChannelPid, Handle, Len) -> {ok, Data} | eof | Error
              when
                  ChannelPid :: pid(),
                  Handle :: term(),
                  Len :: integer(),
                  Data :: string() | binary(),
                  Error :: {error, reason()}.

Equivalent to read/4.

read(ChannelPid, Handle, Len, Timeout)

-spec read(ChannelPid, Handle, Len, Timeout) -> {ok, Data} | eof | Error
              when
                  ChannelPid :: pid(),
                  Handle :: term(),
                  Len :: integer(),
                  Timeout :: timeout(),
                  Data :: string() | binary(),
                  Error :: {error, reason()}.

Reads Len bytes from the file referenced by Handle. Returns {ok, Data}, eof, or {error, reason()}. If the file is opened with binary, Data is a binary, otherwise it is a string.

If the file is read past eof, only the remaining bytes are read and returned. If no bytes are read, eof is returned.

read_file(ChannelPid, File)

-spec read_file(ChannelPid, File) -> {ok, Data} | Error
                   when
                       ChannelPid :: pid(),
                       File :: string(),
                       Data :: binary(),
                       Error :: {error, reason()}.

Equivalent to read_file/3.

read_file(ChannelPid, File, Timeout)

-spec read_file(ChannelPid, File, Timeout) -> {ok, Data} | Error
                   when
                       ChannelPid :: pid(),
                       File :: string(),
                       Data :: binary(),
                       Timeout :: timeout(),
                       Error :: {error, reason()}.

Reads a file from the server, and returns the data in a binary.

read_file_info(ChannelPid, Name)

-spec read_file_info(ChannelPid, Name) -> {ok, FileInfo} | Error
                        when
                            ChannelPid :: pid(),
                            Name :: string(),
                            FileInfo :: file:file_info(),
                            Error :: {error, reason()}.

Equivalent to read_file_info/3.

read_file_info(ChannelPid, Name, Timeout)

-spec read_file_info(ChannelPid, Name, Timeout) -> {ok, FileInfo} | Error
                        when
                            ChannelPid :: pid(),
                            Name :: string(),
                            Timeout :: timeout(),
                            FileInfo :: file:file_info(),
                            Error :: {error, reason()}.

Returns a file_info record from the file system object specified by Name or Handle. See file:read_file_info/2 for information about the record.

Depending on the underlying OS:es links might be followed and info on the final file, directory etc is returned. See read_link_info/2 on how to get information on links instead.

read_link(ChannelPid, Name)

-spec read_link(ChannelPid, Name) -> {ok, Target} | Error
                   when
                       ChannelPid :: pid(),
                       Name :: string(),
                       Target :: string(),
                       Error :: {error, reason()}.

Equivalent to read_link/3.

read_link(ChannelPid, Name, Timeout)

-spec read_link(ChannelPid, Name, Timeout) -> {ok, Target} | Error
                   when
                       ChannelPid :: pid(),
                       Name :: string(),
                       Target :: string(),
                       Timeout :: timeout(),
                       Error :: {error, reason()}.

Reads the link target from the symbolic link specified by name.

read_link_info(ChannelPid, Name)

-spec read_link_info(ChannelPid, Name) -> {ok, FileInfo} | Error
                        when
                            ChannelPid :: pid(),
                            Name :: string(),
                            FileInfo :: file:file_info(),
                            Error :: {error, reason()}.

Equivalent to read_link_info/3.

read_link_info(ChannelPid, Name, Timeout)

-spec read_link_info(ChannelPid, Name, Timeout) -> {ok, FileInfo} | Error
                        when
                            ChannelPid :: pid(),
                            Name :: string(),
                            FileInfo :: file:file_info(),
                            Timeout :: timeout(),
                            Error :: {error, reason()}.

Returns a file_info record from the symbolic link specified by Name or Handle. See file:read_link_info/2 for information about the record.

rename(ChannelPid, OldName, NewName)

-spec rename(ChannelPid, OldName, NewName) -> ok | Error
                when
                    ChannelPid :: pid(),
                    OldName :: string(),
                    NewName :: string(),
                    Error :: {error, reason()}.

Equivalent to rename/4.

rename(ChannelPid, OldName, NewName, Timeout)

-spec rename(ChannelPid, OldName, NewName, Timeout) -> ok | Error
                when
                    ChannelPid :: pid(),
                    OldName :: string(),
                    NewName :: string(),
                    Timeout :: timeout(),
                    Error :: {error, reason()}.

Renames a file named OldName and gives it the name NewName.

start_channel(Dest)

-spec start_channel(ssh:open_socket() | ssh:connection_ref() | ssh:host()) ->
                       {ok, pid()} | {ok, pid(), ssh:connection_ref()} | {error, reason()}.

Equivalent to start_channel/2.

start_channel/2

-spec start_channel(ssh:open_socket(), [ssh:client_option() | sftp_option()]) ->
                       {ok, pid(), ssh:connection_ref()} | {error, reason()};
                   (ssh:connection_ref(), [ssh:client_option() | sftp_option()]) ->
                       {ok, pid()} | {ok, pid(), ssh:connection_ref()} | {error, reason()};
                   (ssh:host(), [ssh:client_option() | sftp_option()]) ->
                       {ok, pid(), ssh:connection_ref()} | {error, reason()}.

Starts new ssh channel for communicating with the SFTP server.

Starts an ssh channel when first argument is a connection reference.

Equivalent to start_channel(Host, 22, UserOptions) when first argument is recognized as network host.

Otherwise, first argument is treated as a network socket which will be used for establishing new SSH connection. New connection reference will be used for starting an SSH channel.

The returned pid for this process is to be used as input to all other API functions in this module.

See also (start_channel/3).

start_channel(Host, Port, UserOptions0)

-spec start_channel(ssh:host(), inet:port_number(), [ssh:client_option() | sftp_option()]) ->
                       {ok, pid(), ssh:connection_ref()} | {error, reason()}.

Starts new ssh connection and channel for communicating with the SFTP server.

The returned pid for this process is to be used as input to all other API functions in this module.

Options:

{timeout, timeout()} - There are two ways to set a timeout for the underlying ssh connection:

If the connection timeout option connect_timeout is set, that value is used also for the negotiation timeout and this option (timeout) is ignored.

Otherwise, this option (timeout) is used as the negotiation timeout only and there is no connection timeout set

The value defaults to infinity.

{sftp_vsn, integer()} - Desired SFTP protocol version. The actual version is the minimum of the desired version and the maximum supported versions by the SFTP server.

All other options are directly passed to ssh:connect/3 or ignored if a connection is already provided.

stop_channel(ChannelPid)

-spec stop_channel(ChannelPid) -> ok when ChannelPid :: pid().

Stops an SFTP channel. Does not close the SSH connection. Use ssh:close/1 to close it.

write(ChannelPid, Handle, Data)

-spec write(ChannelPid, Handle, Data) -> ok | Error
               when ChannelPid :: pid(), Handle :: term(), Data :: iodata(), Error :: {error, reason()}.

Equivalent to write/4.

write(ChannelPid, Handle, Data, Timeout)

-spec write(ChannelPid, Handle, Data, Timeout) -> ok | Error
               when
                   ChannelPid :: pid(),
                   Handle :: term(),
                   Data :: iodata(),
                   Timeout :: timeout(),
                   Error :: {error, reason()}.

Writes data to the file referenced by Handle. The file is to be opened with write or append flag. Returns ok if successful or {error, reason()} otherwise.

write_file(ChannelPid, File, Data)

-spec write_file(ChannelPid, File, Data) -> ok | Error
                    when
                        ChannelPid :: pid(),
                        File :: string(),
                        Data :: iodata(),
                        Error :: {error, reason()}.

Equivalent to write_file/4.

write_file(ChannelPid, File, Data, Timeout)

-spec write_file(ChannelPid, File, Data, Timeout) -> ok | Error
                    when
                        ChannelPid :: pid(),
                        File :: string(),
                        Data :: iodata(),
                        Timeout :: timeout(),
                        Error :: {error, reason()}.

Writes a file to the server. The file is created if it does not exist but overwritten if it exists.

write_file_info(ChannelPid, Name, FileInfo)

-spec write_file_info(ChannelPid, Name, FileInfo) -> ok | Error
                         when
                             ChannelPid :: pid(),
                             Name :: string(),
                             FileInfo :: file:file_info(),
                             Error :: {error, reason()}.

Equivalent to write_file_info/4.

write_file_info(ChannelPid, Name, FileInfo, Timeout)

-spec write_file_info(ChannelPid, Name, FileInfo, Timeout) -> ok | Error
                         when
                             ChannelPid :: pid(),
                             Name :: string(),
                             FileInfo :: file:file_info(),
                             Timeout :: timeout(),
                             Error :: {error, reason()}.

Writes file information from a file_info record to the file specified by Name. See file:write_file_info/2,3 for information about the record.

ssh_sftpd

Specifies the channel process to handle an SFTP subsystem.

Specifies a channel process to handle an SFTP subsystem.

Summary

Functions

subsystem_spec(Options)

Is to be used together with ssh:daemon/[1,2,3]

Functions

subsystem_spec(Options)

-spec subsystem_spec(Options) -> Spec
                        when
                            Options ::
                                [{cwd, string()} |
                                 {file_handler, CbMod | {CbMod, FileState}} |
                                 {max_files, integer()} |
                                 {max_handles, integer()} |
                                 {max_path, integer()} |
                                 {root, string()} |
                                 {sftpd_vsn, integer()}],
                            Spec :: {Name, {CbMod, Options}},
                            Name :: string(),
                            CbMod :: atom(),
                            FileState :: term().

Is to be used together with ssh:daemon/[1,2,3]

The Name is "sftp" and CbMod is the name of the Erlang module implementing the subsystem using the ssh_server_channel (replaces ssh_daemon_channel) behaviour.

Options:

cwd - Sets the initial current working directory for the server.

file_handler - Determines which module to call for accessing the file server. The default value is ssh_sftpd_file, which uses the file and filelib APIs to access the standard OTP file server. This option can be used to plug in other file servers.

max_files - The default value is 0, which means that there is no upper limit. If supplied, the number of filenames returned to the SFTP client per READDIR request is limited to at most the given value.

max_handles - The default value is 1000. Positive integer value represents the maximum number of file handles allowed for a connection.

(Note: separate limitation might be also enforced by underlying operating system)

max_path - The default value is 4096. Positive integer value represents the maximum path length which cannot be exceeded in data provided by the SFTP client. (Note: limitations might be also enforced by underlying operating system)

root - Sets the SFTP root directory. Must be an absolute path (e.g., /tmp). Then the user cannot see any files above this root. If, for example, the root directory is set to /tmp, then the user sees this directory as /. If the user then writes cd /etc, the user moves to /tmp/etc.

Note: This provides application-level isolation. For additional security, consider using OS-level chroot or similar mechanisms. See the SFTP subsystem section in the Hardening guide for deployment recommendations.

sftpd_vsn - Sets the SFTP version to use. Defaults to 5. Version 6 is under development and limited.