sftp
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
Syntax
Description
s = sftp(
uses the key files at the specified locations.host
,user
,"PublicKeyFile",publickeyfile
,"PrivateKeyFile",privatekeyfile
)
s = sftp(___,
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
Name,Value
)"ServerSystem"
as "Windows"
to connect to an SFTP
server that runs on a Windows® operating system.
Input Arguments
host
— Hostname of SFTP server
string scalar | character vector
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")
.
user
— Name of authorized account
string scalar | character vector
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
— Password for specified account
string scalar | character vector
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.
Example: "Password","PaSsWoRd123"
publickeyfile
— Public key file for SFTP authentication
string scalar | character vector
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"
privatekeyfile
— Private key file for SFTP authentication
string scalar | character vector
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"
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")
DatetimeType
— Type to use for the dir
output date field
"datetime"
(default) | "text"
Type to use for the dir
output date field, specified as
"datetime"
or "text"
.
StartingFolder
— Folder to use as the remote current working folder at login
string scalar | character vector
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"
ServerSystem
— Type of operating system running on the SFTP server
"unix"
(default) | "Windows"
Type of operating system running on the SFTP server, specified as either
"unix"
or "Windows"
.
ServerLocale
— Locale for reading dates from the remote server
"en_US"
(default) | string scalar | character vector
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
,
where xx
_YY
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 | Language | Country |
---|---|---|
"de_DE" | German | Germany |
"en_GB" | English | United Kingdom |
"en_US" | English | United States |
"es_ES" | Spanish | Spain |
"fr_FR" | French | France |
"it_IT" | Italian | Italy |
"ja_JP" | Japanese | Japan |
"ko_KR" | Korean | Korea |
"nl_NL" | Dutch | Netherlands |
"zh_CN" | Chinese (simplified) | China |
DirParserFcn
— How to parse the FTP server's LIST command output
function handle
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:
The list of directory entries, specified as a string vector.
The server locale, specified as a string scalar.
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
ConnectionTimeout
— Maximum time allowed for connection
300 seconds (default) | duration
scalar
Since R2024b
Maximum time allowed for a connection, specified as a duration
scalar. By default, a connection ends after 300 seconds.
TransferTimeout
— Maximum time allowed for transfer
duration
scalar
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.
PrivateKeyPassphrase
— Passphrase for private key
string scalar | character vector
Since R2024b
Passphrase for the private key, specified as a string scalar or character vector.
CertificateFilename
— Certificate filename
"default"
(default) | string scalar | character vector
Since R2024b
Certificate filename, specified as "default"
, 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.
If CertificateFilename
is "default"
,
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
cd | Change or view current folder on SFTP or FTP server |
close | Close connection to SFTP or FTP server |
delete | Delete file on SFTP or FTP server |
dir | List folder contents on SFTP or FTP server |
mget | Download files from SFTP or FTP server |
mkdir | Make new folder on SFTP or FTP server |
mput | Upload file or folder to SFTP or FTP server |
rename | Rename file on SFTP or FTP server |
rmdir | Remove folder on SFTP or FTP server |
Examples
Connect to an SFTP server
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"
Download File and List Contents of Folders
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)
Specify Values for Server Locale and Parsing LIST
Command Output
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"
Specify the Datetime Datatype for LIST
Command Output
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 R2021bR2024b: Specify time-out values for connections and transfers
You can specify the maximum amount of time allowed for a connection and for a transfer
by using the ConnectionTimeout
and TransferTimeout
name-value arguments, respectively.
R2024b: Connect to servers that require passphrases or certificates
You can connect to servers with passphrases and certificates by using the
PrivateKeyPassphrase
and CertificateFilename
name-value arguments, respectively.
R2024a: Specify remote current working folder at login
When you connect to an SFTP server, you can specify a remote current working folder by
using the StartingFolder
name-value argument.
See Also
Comando de MATLAB
Ha hecho clic en un enlace que corresponde a este comando de MATLAB:
Ejecute el comando introduciéndolo en la ventana de comandos de MATLAB. Los navegadores web no admiten comandos de MATLAB.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)