ftp
Connection to FTP server to access its files
Description
Connect to an FTP server by calling the ftp
function,
which creates an FTP connection object. Then, use the FTP connection object to upload
and download files. You also can create, delete, and navigate to different folders on
the server. To close the connection, use the close
function.
Because FTP is not a secure protocol, it does not encrypt your user name, your
password, or any data you download from or upload to an FTP server. If you require a
secure FTP connection, use sftp
.
Creation
Syntax
Description
ftpobj = ftp(
opens a
connection to the FTP server host
)host
and returns an FTP
connection object. You can only use this syntax with hosts that support
anonymous (unauthenticated) connections.
ftpobj = ftp(
specifies options using one or more name-value arguments. For example, you can
specify host
,username
,password
,Name,Value
)"System"
as "Windows"
to connect
to an FTP server that runs on a Windows® operating system, or specify
"LocalDataConnectionMethod"
as
"active"
to change the connection mode from passive to
active mode.
Input Arguments
host
— Hostname of FTP server
string scalar | character vector
Hostname of FTP server, specified as a string scalar or character vector.
The default port number for FTP servers is 21. 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
ftp
, as in "ftp.example.com"
.
However, this practice is a convention, not a technical requirement. For
example, ftpobj = ftp("www.example.com:20")
opens an
anonymous connection to port number 20 if the server
www.example.com
is configured to provide FTP
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: ftpobj = ftp("ftp.example.com")
username
— Name of authorized account
string scalar | character vector
Name of an authorized account on the FTP server, specified as a string
scalar or character vector. The FTP object sends
username
as plain text.
password
— Password for authorized account
string scalar | character vector
Password for an authorized account, specified as a string scalar or
character vector. The FTP object sends password
as
plain text.
To increase security, avoid hard-coding sensitive information, such as passwords. For more information, see Keep Sensitive Information Out of Code.
Example: ftpobj =
ftp("ftp.example.com","myusername","mypassword")
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: ftpobj =
ftp(host,username,password,System="Windows")
Before R2021a, use commas to separate each name and value, and enclose
Name
in quotes.
Example: ftpobj =
ftp(host,username,password,"System","Windows")
System
— Type of operating system running on FTP server
"unix"
(default) | "Windows"
Type of operating system running on the FTP server, specified as
the name-value argument consisting of "System"
and either "unix"
or
"Windows"
.
The FTP connection object autodetects the server's operating system.
The FTP dir
function might return less
information if the FTP connection object is not configured for the
operating system running on the FTP server. In such cases,
dir
might return a structure array with
some empty fields. In that case, call ftp
again
and specify the correct value for the "System"
name-value argument to specify the correct operating system.
LocalDataConnectionMethod
— Connection mode
"passive"
(default) | "active"
Connection mode, specified as the name-value argument consisting
of "LocalDataConnectionMethod"
and either
"passive"
or
"active"
.
There are two modes for establishing an FTP connection. Most
modern FTP implementations use passive
mode, but
to connect to some legacy servers, you might need to specify
active
mode.
"passive"
— Your machine establishes both channels. After establishing the command channel, your machine requests that the FTP server start listening on a port, so that your machine can connect to that port."active"
— Your machine establishes a channel for commands, but the FTP server establishes a channel for data. Active mode can be a problem if, for example, your machine is protected by a firewall and does not allow unauthorized session requests from external sources.
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 the
name-value argument consisting of
"ServerLocale"
and a string scalar or character
vector.
The ServerLocale
value can be:
A character vector or string scalar in the form
, wherexx
_YY
xx
is a lowercase ISO 639-1 two-letter code that specifies a language, andYY
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 FTP server's LIST command output, specified as
the name-value argument consisting of
"DirParserFcn"
and a function handle. The
default value is either
@matlab.io.ftp.parseDirListingForUnix
or
@matlab.io.ftp.parseDirListingForWindows
,
depending on the server's operating system.
A custom function handle must have two inputs:
The list of directory entries, specified as a string vector.
The server locale, specified as a string scalar.
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
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 two input arguments,
list of directory entries, entries
and server
locale,
serverLocale
:
function listing = myFormatFcn(entries,serverLocale)
Example Function
Join the entries into a cell array that will be input to textscan:
function listing = myFormatFcn(entries,serverLocale) 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); listing(ii).date = datestr(thisDate); listing(ii).datenum = datenum(thisDate); end end
Mode
— Transfer mode for FTP
server
"binary"
(default) | "ascii"
Transfer mode for FTP server, specified as the name-value argument
consisting of "Mode"
and
"binary"
or "ascii"
. Use
ASCII mode for text files, such as HTML pages and Rich Text Format
(RTF) files. Use the binary mode for nontext files, such as
executable files or zip archives.
Once you create an FTP object, use the ascii and binary functions to change the transfer mode. You may need to change modes to transfer files of different types. Transfer mode settings persist until the end of your MATLAB session or until you change them.
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 FTP transfer does not time
out.
TLSMode
— Connection to server using TLS/SSL
"none"
(default) | "strict"
| "opportunistic"
Since R2024b
Connection to the server using TLS/SSL, specified as one of these values:
"none"
— Do not connect to the server using TLS/SSL. Use plain-text data transfer between the client and server."strict"
— Ensure that a TLS/SSL connection is established between the client and server. If a TLS/SSL connection is not possible, the connection fails and returns an error."opportunistic"
— Use a TLS/SSL connection if possible. If a TLS/SSL connection is not possible, the FTP connection uses plain-text data transfer between the client and server.
TLS (Transport Layer Security), sometimes referred to as SSL (Secure Sockets Layer), is a security protocol that encrypts communication between the client and server.
Note
Security Considerations: To
increase the security of your workflow, specify
TLSMode
as "strict"
if
your FTP server supports TLS/SSL connections.
Object Functions
ascii | Set FTP transfer mode to ASCII |
binary | Set FTP transfer mode to binary |
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
Download File and List Contents of Folders
To open a connection to an FTP server, create an FTP object. Use the FTP object to download a file and list the contents of subfolders on the server. At the end of the FTP session, close the connection.
First, connect to the National Centers for Environmental Information (NCEI) FTP server.
ftpobj = ftp("ftp.ngdc.noaa.gov")
FTP with properties: Host: "ftp.ngdc.noaa.gov" Username: "anonymous" Port: 21 ServerLocale: "en_US" DirParserFcn: @matlab.io.ftp.parseDirListingForUnix Mode: "binary" LocalDataConnectionMethod: "passive" RemoteWorkingDirectory: "/" CertificateFilename: "default" ConnectionTimeout: 5 min TransferTimeout: Inf sec
List the contents of the top-level folder on the FTP server.
dir(ftpobj)
DMSP INDEX.txt README.txt STP Snow_Ice Solid_Earth coastwatch dmsp4alan ftp.html geomag google12c4c939d7b90761.html index.html international ionosonde mgg pub wdc
Download the README.txt
file from the FTP server. The mget
function downloads a copy to your current MATLAB® folder.
mget(ftpobj,"README.txt");
Read the contents of your copy of README.txt
using the readlines
function.
readme = readlines("README.txt");
readme(1:4)
ans = 4×1 string
" Welcome to the "
" NOAA/National Centers for Environmental Information (NCEI), "
" formerly the National Geophysical Data Center (NGDC)"
" FTP area"
List the contents of a subfolder using the dir
function.
dir(ftpobj,"STP")
ANOMALIES DMSP ECLIPSE GEOMAGNETIC_DATA GOIN GPS_GNSS IONOSPHERE NOAA SEIS SGD SOLAR_DATA SPIDR STEP SWA Solid_Earth aavso_22nov16 aeronomy cdroms goesr ionosonde log.txt publications satellite_data space-weather space_environment_modeling swpc_products temp tivoli
Change to a subfolder using the cd
function. The output from cd
is the path to the current folder on the FTP server, not your current MATLAB folder.
cd(ftpobj,"STP/space-weather")
ans = '/STP/space-weather'
List the contents of the current folder on the FTP server.
dir(ftpobj)
aurora-airglow denig-files documentation geomagnetic-data interplanetary-data ionospheric-data online-publications satellite-data solar-data spacecraft-environments
Close the connection to the FTP server. You also can close the connection by deleting the FTP object or letting the connection time out.
close(ftpobj)
FTP service courtesy of the National Centers for Environmental Information (NCEI). See the NCEI Privacy Policy, Disclaimer, and Copyright for NCEI terms of service.
Specify Values for Server Locale and Parsing LIST
Command Output
Connect to the National Centers for Environmental Information (NCEI) FTP server. Specify the server locale as United Kingdom. Specify the FTP server's LIST
command output to be parsed relative to Windows using the name-value argument "DirParserFcn"
.
ftpobj = ftp("ftp.ngdc.noaa.gov","ServerLocale","en_GB","DirParserFcn",@matlab.io.ftp.parseDirListingForWindows)
FTP with properties: Host: "ftp.ngdc.noaa.gov" Username: "anonymous" Port: 21 ServerLocale: "en_GB" DirParserFcn: @matlab.io.ftp.parseDirListingForWindows Mode: "binary" LocalDataConnectionMethod: "passive" RemoteWorkingDirectory: "/" CertificateFilename: "default" ConnectionTimeout: 5 min TransferTimeout: Inf sec
FTP service courtesy of the National Centers for Environmental Information (NCEI). See the NCEI Privacy Policy, Disclaimer, and Copyright for NCEI terms of service.
Tips
The FTP object does not support proxy server settings.
Pass the
~
symbol to thecd
function to navigate to the login folder.
Version History
Introduced before R2006aR2024b: 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: Enable TLS when connecting to FTP servers
When you connect to an FTP server, you can enable Transport Layer Security (TLS)
using the TLSMode
name-value argument.
See Also
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
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)