ssh_sftp(3)

πŸ“¦
version 29.0.6 Β· 3 versions
, in ubuntu stonking

πŸ¦‹ ssh_sftp β€” the SFTP client module (Erlang Module Definition, section 3)

okay bestie, buckle up πŸ’– this is ssh_sftp, and she is that girl. Manual section 3, Erlang module. Let's get into it.


✨ NAME ✨

ssh_sftp β€” SFTP client. periodt.


πŸ’– DESCRIPTION πŸ’–

So this module implements an SSH FTP (SFTP) client. SFTP is a secure, encrypted file transfer service that's available for SSH. no cap, that's the whole vibe: move files around over SSH, but encrypted and cute about it. πŸ”


πŸŽ€ DATA TYPES πŸŽ€

chunk_size() :: undefined | pos_integer().


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


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

The initial crypto_state/0 that came back from the init_fun/0 gets folded into repeated applications of the crypto_fun/0 in the tar_crypto_spec. The binary that fun hands back gets sent to the remote SFTP server, and the new crypto_state/0 is what gets used in the next call of crypto_fun/0. πŸ’«

And if the crypto_fun/0 returns a chunk_size/0? That value is used as block size for further blocks in calls to crypto_fun/0.


crypto_state() :: any().

The init_fun/0 in the tar_crypto_spec is applied once, prior to any other crypto operation. The whole intention here is that this function kicks off the encryption or decryption β€” like, for example, by calling crypto:crypto_init/4 or something similar. The crypto_state/0 is the state a function like that may return. 🧚

If the selected cipher needs its input data partitioned into blocks of a certain size, then the init_fun/0 should return the second form of return value with the chunk_size/0 set to the block size. If chunk_size/0 is undefined, then the size of the PlainBins varies, because that's intended for stream crypto β€” whereas a fixed chunk_size/0 is intended for block crypto. And yes, a chunk_size/0 can be changed in the return from the crypto_fun/0. The value can flip back and forth between pos_integer/0 and undefined. πŸ”„


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

Specifies the encryption or decryption that gets applied to tar files when you're using open_tar/3 or open_tar/4.

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

For code examples, go peek at Section Example with encryption in the ssh Users Guide. πŸ“–


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


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

If you're doing encryption, the final_fun/0 in the tar_crypto_spec gets applied to the last piece of data. The final_fun/0 is the one responsible for the padding (if it's needed) and the encryption of that last piece. she does the finishing touches πŸ’…


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


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

A description of 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 SSH_FX_*, which get transformed into the lowercase version 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 the case of an exit-signal. If that information is empty, the reason is the exit signal name.

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


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

Specifies the available SFTP options. ⭐


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


πŸ”₯ FUNCTIONS πŸ”₯

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. two-for-one, iconic 🫢


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. same energy ✨


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 that's guaranteed to be unique between calls of aread. The actual data gets sent as a message to the calling process. That 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) -> {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 gets sent as a message to the calling process. That message has the form {async_reply, N, Result}, where Result is the result from the write β€” either ok, or {error, reason()}. πŸ’Œ


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. say bye bestie πŸ‘‹


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. no clutter allowed 🧹


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, 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. a whole little roster of files, cute πŸ“‹


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 inside an existing directory β€” so no manifesting a whole path out of the void, bestie. 🌱


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, 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 you can use for reading or writing. πŸ”‘


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. That 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. don't do it twice, she's got it handled.

For code examples, check Section SFTP Client with TAR Compression in the ssh Users Guide.

The crypto mode option is explained up in the data types section, see Crypto operations for open_tar. Encryption is assumed if the Mode contains write, and decryption if the Mode contains read. πŸ—œοΈβœ¨


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. That handle can be used for reading directory contents. πŸ“‚


✨ position/4 ✨

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()}.

Okay so bestie, this one sets the file position of the file that Handle is pointing at πŸ’…. If it vibes, you get {ok, NewPosition} back β€” and that's an absolute offset, no cap β€” otherwise it's {error, reason()}. Location can be any one of these:

  • Offset β€” literally the same as {bof, Offset}.
  • {bof, Offset} β€” absolute offset, full send from the top πŸŽ€.
  • {cur, Offset} β€” offset counted from wherever you're standing right now.
  • {eof, Offset} β€” offset from the end of file.
  • bof | cur | eof β€” same as earlier but with Offset of 0, that is {bof, 0} | {cur, 0} | {eof, 0}. The lazy-girl shortcut, iconic honestly.

πŸ¦‹ pread/3,4 πŸ¦‹

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 β€” it's giving collab era, because it's literally position/3 and read/3,4 combined into one ✨.


πŸ’– pwrite/3,4 πŸ’–

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. Same energy, but the write-flavoured sibling 🫢.


🌸 read/3,4 🌸

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 that Handle is referencing πŸ“–. You get back {ok, Data}, or eof, or {error, reason()}.

Quick tea: if the file is opened with binary, then Data is a binary. Otherwise? It's a string. Easy.

And if you read past eof, only the remaining bytes get read and returned β€” no drama, it just gives you what's left. But if literally no bytes are read at all, then you get eof back. Periodt πŸ’€.


✨ read_file/3 ✨

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 hands you the data in a binary. Lowkey the simplest one here πŸŽ€.


πŸ‘‘ read_file_info/3 πŸ‘‘

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 whatever file system object Name or Handle is pointing to 🫢. Wanna know what's actually inside that record? Go read file:read_file_info/2, it spills all the details.

Real talk though: depending on the underlying OS:es, links might get followed and you'll get the info on the final file, directory, etc. If you want the tea on the link itself instead, hit up read_link_info/2 🌈.

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. That's it, that's the function πŸ”₯.


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 β€” so the link itself, not whatever it points at, main character energy only πŸ’…. For the full breakdown of that record, see file:read_link_info/2.


πŸ’œ rename/4 πŸ’œ

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. Glow-up arc, fr fr ✨.


🌈 start_channel/2 🌈

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 a new ssh channel for communicating with the SFTP server, bestie 🌸. The way it decides what to do depends on what you hand it first:

  • If the first argument is a connection reference, it starts an ssh channel. Simple as that.
  • If the first argument gets recognized as a network host, it's equivalent to start_channel(Host, 22, UserOptions).
  • Otherwise, the first argument is treated as a network socket, and that socket will be used for establishing a new SSH connection. That new connection reference then gets used for starting an SSH channel.

The returned pid for this process is what you feed into every other API function in this module β€” don't lose it 🫢.

See also (start_channel/3).


πŸ’… start_channel/3 πŸ’…

start_channel(ssh:host(),
                     inet:port_number(),
                     [ssh:client_option() | sftp_option()]) ->
                        {ok, pid(), ssh:connection_ref()} |
                        {error, reason()}.

Starts a new ssh connection and channel for communicating with the SFTP server. Again: the pid that comes back is your golden ticket, use it as input to all the other API functions in this module πŸ‘‘.

The options, let's go:

  • {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. Sorry girl, it's not her moment.
    • 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()} β€” the desired SFTP protocol version. The actual version is the minimum of the desired version and the maximum supported versions by the SFTP server. So babe, you can ask, but the server has the final say πŸ’€.

All other options are directly passed to ssh:connect/3 β€” or ignored if a connection is already provided.


πŸŽ€ stop_channel/1 πŸŽ€

stop_channel(ChannelPid) -> ok when ChannelPid :: pid().

Stops an SFTP channel. Bestie, listen: this does NOT close the SSH connection. If you want the connection gone too, use ssh:close/1 🌸.


πŸ¦‹ write/4 πŸ¦‹

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

Writes data to the file that Handle is referencing ✍️. The file is to be opened with the write or append flag β€” don't forget that part or it's not gonna hit. Returns ok if it slays, or {error, reason()} otherwise.


πŸ’– write_file/4 πŸ’–

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 πŸ“. If the file doesn't exist, it gets created. But if it does exist? It gets overwritten. No merge, no warning, just replacement. Be careful out there πŸ™ˆ.


⭐ write_file_info/4 ⭐

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. Want the whole rundown on that record? See file:write_file_info/2,3 πŸŽ€.


That's a wrap on the whole page, bestie πŸ’œ and it's brought to you by Ericsson AB β€” this is ssh version 6.0.5, and the page you just read is the iconic ssh_sftp(3). Go forth and sftp responsibly βœ¨πŸ‘‘πŸ’…

πŸ“¦ where this page comes from