Main Content

sftp

Connection to SFTP server to access its files

Since R2021b

Description

Connect to an SFTP server by calling the sftp function, which creates an SFTP connection object. To access a particular SFTP account on the server, specify a host and a user. Then, use the SFTP object to upload, download, and delete files. You also can create, delete, and navigate to different folders on the server. To close the connection, use the close function.

Because SFTP is a secure protocol, the SFTP object encrypts your username, your password, and any data you download from or upload to an SFTP server.

Creation

Description

s = sftp(host,user) opens a connection between the user and the SFTP server host and returns an SFTP connection object. SSH keys are retrieved from the default location.

example

s = sftp(host,user,PrivateKeyFile=privatekeyfile) uses the specified private key file.

s = sftp(host,user,PrivateKeyFile=privatekeyfile,PrivateKeyPassphrase=passphrase) uses the specified private key file and associated passphrase.

s = sftp(host,user,PublicKeyFile=publickeyfile,PrivateKeyFile=privatekeyfile) uses the specified public and private key files.

s = sftp(host,user,PublicKeyFile=publickeyfile,PrivateKeyFile=privatekeyfile,PrivateKeyPassphrase=passphrase) uses the specified public and private key files as well as private key passphrase.

s = sftp(___,Name=Value) specifies options using one or more name-value arguments in addition to any of the input argument combinations in previous syntaxes. For example, you can specify the value of ServerSystem as "Windows" to connect to an SFTP server that runs on a Windows® operating system.

example

Input Arguments

expand all

Hostname of the SFTP server, specified as a string scalar or character vector.

The default port number for SFTP servers is 22. To specify an alternate port number for the connection, append a colon (:) and the port number to host.

Typically, the hostname of a server starts with "sftp", as in "sftp.example.com". However, this practice is a convention, not a technical requirement. For example, s = sftp("www.example.com:22") opens an anonymous connection to port number 22 if the server www.example.com is configured to provide SFTP service.

Rather than hard-coding configuration data, you can store and retrieve this sensitive information from your MATLAB® vault or a .env file. For more information, see Keep Sensitive Information Out of Code.

Example: "sftp.example.com"

Example: "sftp.example.com:2222"

Name of an authorized account on the SFTP server, specified as a string scalar or character vector. The SFTP object sends user as plain text.

To specify a password for the user account, use the Password name-value argument.

Public key file for SFTP authentication, specified as a string scalar or character vector. The default location of the public key file depends on your operating system.

  • On Linux® and macOS, the default location of the public key file is "$HOME/.ssh/id_rsa.pub".

  • On Windows, the default location of the public key file is "%USERPROFILE%\.ssh\id_rsa.pub".

Example: publickeyfile="/Users/abc/sshKeys/keys.pub"

Private key file for SFTP authentication, specified as a string scalar or character vector. The default location of the private key file depends on your operating system.

  • On Linux and macOS, the default location of the private key file is "$HOME/.ssh/id_rsa".

  • On Windows, the default location of the private key file is "%USERPROFILE%\.ssh\id_rsa".

To specify a passphrase for the private key file, use the passphrase argument.

Example: PrivateKeyFile="/Users/abc/sshKeys/keys"

Since R2024b

Passphrase for the private key, specified as a string scalar or character vector.

To increase security, avoid hard-coding sensitive information, such as passphrases. For more information, see Keep Sensitive Information Out of Code.

Name-Value Arguments

expand all

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: s = sftp(host,user,ServerSystem="Windows")

Password for the specified account, specified as a string scalar or character vector. The SFTP object sends Password as encrypted text.

To increase security, avoid hard-coding sensitive information, such as passwords. For more information, see Keep Sensitive Information Out of Code.

Type to use for the date field of dir output, specified as "datetime" or "text". By default, the dir function returns the date field as a datetime value. Specify "text" to return the date field as a character value.

Since R2024a

Folder to use as the remote current working folder at login, specified as a string scalar or character vector. By default, the remote current working folder is the home folder of the user account on the server.

Example: StartingFolder="home/jsmith/birds"

Type of operating system running on the SFTP server, specified as either "unix" or "Windows".

Locale for reading dates from the remote server, specified as a string scalar or character vector.

The ServerLocale value can be a string scalar or character vector in the form xx_YY, where xx is a lowercase ISO 639-1 two-letter code that specifies a language, and YY is an uppercase ISO 3166-1 alpha-2 code that specifies a country.

This table lists some common values for the locale.

Locale LanguageCountry
"de_DE"GermanGermany
"en_GB"EnglishUnited Kingdom
"en_US"EnglishUnited States
"es_ES"SpanishSpain
"fr_FR"FrenchFrance
"it_IT"ItalianItaly
"ja_JP"JapaneseJapan
"ko_KR"KoreanKorea
"nl_NL"DutchNetherlands
"zh_CN"Chinese (simplified)China

How to parse the dir output from the server, specified as a function handle. The default value is either @matlab.io.ftp.parseDirListingForUnix or @matlab.io.ftp.parseDirListingForWindows, depending on the operating system of the server. If the default value results in an error referencing the inability to parse the dir output (when you call dir or any object function that references dir), specify this name-value argument.

You can specify a custom function handle. A custom function handle must have the function signature function listing = myFormatFcn(entries,serverLocale,datetimeType), where:

  1. The input entries is the list of directory entries, specified as a string vector.

  2. The input serverLocale is the server locale, specified as a string scalar.

  3. The input datetimeType is the data type for date and time data, specified as "datetime" or "text".

The output listing of the custom function handle must be a structure array of size m-by-1, where m is the number of items in the folder. The fields of the structure must match the fields of the structure returned by the dir function: name, isdir, bytes, date, and datenum.

Example Function

Specify a custom function that joins the directory entries into a cell array, which can be used as an input to the textscan function. Preallocate a struct array. Get the individual parts from the textscan output. Populate the structure array with the expected fields.

function listing = myFormatFcn(entries,serverLocale,datetimeType)
    entries = join(entries,newline);
    out = textscan(entries,"%s%d%3c%d%s",MultipleDelimsAsOne=true);
    structSize = numel(out{1});
    listing = struct("name",cell(structSize,1),"isdir",zeros(1,1), ...
        "bytes",zeros(1,1),"date",'',"datenum",zeros(1,1));
    monthName = string(out{3});
    day = string(out{4});
    time = string(out{5});
    names = out{1};
    bytes = out{2};
    for ii = 1:structSize
        listing(ii).name = names{ii};
        listing(ii).isdir = false;
        listing(ii).bytes = bytes(ii);
        makeDate = day(ii) + "-" + monthName(ii) + " " + ...
            time(ii);
        thisDate = datetime(makeDate,InputFormat="dd-MMM HH:mm", ...
            Locale=serverLocale);
        if datetimeType == "text"
            listing(ii).date = datestr(thisDate);
        else
            listing(ii).date = thisDate;
        end
        listing(ii).datenum = datenum(thisDate);    
    end
end

Since R2024b

Maximum time allowed for a connection, specified as a duration scalar. By default, a connection ends after 5 minutes.

Since R2024b

Maximum time allowed for a transfer, specified as a duration scalar. If you do not specify a value, an SFTP transfer does not time out.

Since R2024b

Certificate filename, specified as a string scalar, or character vector, denoting the name and location of a file that contains root certificates. The file must be in privacy-enhanced mail (PEM) format, with the header -----BEGIN CERTIFICATE----- and the footer -----END CERTIFICATE-----.

The location of the certificate file must be in the current folder or in a folder on the MATLAB path. You can specify a full or relative path to the certificate file. MATLAB uses the certificates contained in this file to validate server certificates for HTTPS connections. Because the security of HTTPS connections depends on the integrity of this file, protect it appropriately. MATLAB does not manage certificates or certificate files, but third-party tools are available for managing PEM files.

By default, CertificateFilename is "default" and MATLAB validates server certificates using the system-provided certificate store. If you encounter a server certificate validation failure, then check the connection using your system browser.

If you encounter a connection issue, you can take one of these actions:

  • For an expired or revoked server certificate, contact the website owner or server administrator.

  • For a missing root certificate authority (Root CA) certificate, add the Root CA certificate to the file denoted by CertificateFilename.

Object Functions

cdChange or view current folder on SFTP or FTP server
closeClose connection to SFTP or FTP server
deleteDelete file on SFTP or FTP server
dirList folder contents on SFTP or FTP server
mgetDownload files from SFTP or FTP server
mkdirMake new folder on SFTP or FTP server
mputUpload file or folder to SFTP or FTP server
renameRename file on SFTP or FTP server
rmdirRemove folder on SFTP or FTP server

Examples

collapse all

Connect to the example SFTP server.

s = sftp("sftp.example.net","jsmith")
  SFTP with properties:

                         Host: "sftp.example.net"
                     Username: "jsmith"
                         Port: 22
               StartingFolder: "/"
                 ServerSystem: "unix"
                 DatetimeType: "datetime"
                 ServerLocale: "en_US"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForUnix
       RemoteWorkingDirectory: "/home/jsmith"
            ConnectionTimeout: 5 min
              TransferTimeout: Inf min
          CertificateFilename: "default"

Open a connection to an SFTP server by creating an SFTP object. Download a file and list the contents of subfolders on the server using the SFTP object. At the end of the SFTP session, close the connection.

First, connect to the example SFTP server.

s = sftp("sftp.example_galapagos.net","jsmith",Password="PaSsWoRd123")
  SFTP with properties:

                         Host: "sftp.example_galapagos.net"
                     Username: "jsmith"
                         Port: 22
               StartingFolder: "/"
                 ServerSystem: "unix"
                 DatetimeType: "datetime"
                 ServerLocale: "en_US"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForUnix
       RemoteWorkingDirectory: "/home/jsmith"
            ConnectionTimeout: 5 min
              TransferTimeout: Inf min
          CertificateFilename: "default"

List the contents of the top-level folder.

dir(s)
 
air_quality                  fish                        insects                       README.txt
birds                        INDEX.txt                   mammals                       reptiles
climate                      index.html                  rainfall                      sftp.html
 

Download the file README.txt from the SFTP server. The mget function downloads a copy to your current MATLAB folder.

mget(s,"README.txt");

Read the contents of your copy of README.txt using the readlines function. View the first three lines.

readme = readlines("README.txt");
readme(1:3)
ans = 4×1 string
    "                 Welcome to the "
    "    Galapagos Research Institute Data Center "
    "                    SFTP area"

List the contents of a subfolder using the dir function.

dir(s,"home/jsmith/birds")
 
albatrosses                 ducks                       herons                     parrots 
avocets_stilts              falcons                     kingfishers                pelicans
barn_owls                   flamingos                   mockingbirds               penguins 
blackbirds                  frigatebirds                nightjars                  pheasants 
boobies                     grebes                      northern_storm_petrels     pigeons 
cardinal grosbeaks          guineafowl                  osprey                     plovers 
cormorants                  gulls                       owls                       rails
cuckoos                     hawks                       oystercatcher              sandpipers
 

Change to a subfolder using the cd function. The output from cd is the path to the current folder on the SFTP server, not your current MATLAB folder.

cd(s,"home/jsmith/birds/herons")
ans = 
"home/jsmith/birds/herons"

List the contents of the current folder.

dir(s)
documentation             great_egret_data              migration_patterns
great_blue_heron_data     green_heron_data              nesting_behaviors 

Close the connection to the SFTP server. You also can close the connection by deleting the SFTP object or letting the connection time out.

close(s)

Connect to the example SFTP server. Specify the server locale as the United Kingdom. Specify that the dir output for the server is to be parsed relative to Windows using the name-value argument DirParserFcn.

s = sftp("sftp.example_london.net","jsmith", ...
Password="PaSsWoRd123",ServerLocale="en_GB", ...
DirParserFcn=@matlab.io.ftp.parseDirListingForWindows)
  SFTP with properties:

                         Host: "sftp.example_london.net"
                     Username: "jsmith"
                         Port: 22
               StartingFolder: "/"
                 ServerSystem: "unix"
                 DatetimeType: "datetime"
                 ServerLocale: "en_GB"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForUnix
       RemoteWorkingDirectory: "/home/jsmith"
            ConnectionTimeout: 5 min
              TransferTimeout: Inf min
          CertificateFilename: "default"

Connect to the example SFTP server. Instruct the SFTP object to return dates as text.

s = sftp("sftp.example.net","jsmith",DatetimeType="text")
  SFTP with properties:

                         Host: "sftp.example.net"
                     Username: "jsmith"
                         Port: 22
               StartingFolder: "/"
                 ServerSystem: "unix"
                 DatetimeType: "text"
                 ServerLocale: "en_US"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForUnix
       RemoteWorkingDirectory: "/home/jsmith"
            ConnectionTimeout: 5 min
              TransferTimeout: Inf min
          CertificateFilename: "default"

View the date field of the dir output.

d = dir(s);
d.date
ans =

    '03-Dec-2015'

Limitations

  • The SFTP object does not support proxy server settings.

Version History

Introduced in R2021b

expand all