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 will encrypt your user name, your password, and any data you download from or upload to an SFTP server.

Creation

Description

example

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,"PublicKeyFile",publickeyfile,"PrivateKeyFile",privatekeyfile) uses the key files at the specified locations.

example

s = sftp(host,user,"Password",password) uses the password specified.

example

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

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 the 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: s = sftp("sftp.example.com").

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.

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

Example: "Password","PaSsWoRd123"

Public key file for SFTP authentication, specified as a string scalar or character vector. The default location of the public key file is dependent 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 is dependent 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.

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

Name-Value Arguments

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")

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

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

Type to use for the dir output date field, specified as "datetime" or "text".

Since R2024a

Folder to use as the remote current working folder at login, specified as a string scalar or character vector.

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 character vector or string scalar 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 LIST command output from the FTP server, specified as a function handle. The default value is either @matlab.io.ftp.parseDirListingForUnix or @matlab.io.ftp.parseDirListingForWindows, depending on the server's operating system.

You can also specify a custom function handle. A custom function handle must have three inputs:

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

  2. The server locale, specified as a string scalar.

  3. The datatype for date and time data, specified as "datetime" or "text".

The output 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. For more information on these fields, see the dir function reference page.

If the default value results in an error referencing the inability to parse the dir output, specify this name-value argument. This argument must be correctly specified to use object functions that reference dir.

Functional Signature

The custom writing function must accept three input arguments, list of directory entries, entries, server locale, serverLocale, and datatype for date and time data, datetimeType:

function listing = myFormatFcn(entries,serverLocale,datetimeType)

Example Function

Join the entries into a cell array that will be input to textscan. Pre-allocate a struct. Get the individual parts from the textscan output. Construct the struct, populating the appropriate 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

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
                 ServerSystem: "Windows"
                 DatetimeType: "datetime"
                 ServerLocale: "en_US"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForWindows
       RemoteWorkingDirectory: "/home/jsmith"

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
                 ServerSystem: "unix"
                 DatetimeType: "datetime"
                 ServerLocale: "en_US"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForUnix
       RemoteWorkingDirectory: "/home/jsmith"

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 United Kingdom. Specify the SFTP server's LIST command output 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
                 ServerSystem: "Windows"
                 DatetimeType: "datetime"
                 ServerLocale: "en_GB"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForWindows
       RemoteWorkingDirectory: "/home/jsmith"

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
                 ServerSystem: "Windows"
                 DatetimeType: "text"
                 ServerLocale: "en_US"
                 DirParserFcn: @matlab.io.ftp.parseDirListingForWindows
       RemoteWorkingDirectory: "/home/jsmith"

View the date property 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