Main Content

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

Description

example

ftpobj = ftp(host) opens a connection to the FTP server host and returns an FTP connection object. You can only use this syntax with hosts that support anonymous (unauthenticated) connections.

ftpobj = ftp(host,username) accesses the FTP account with the specified user name. You can only use this syntax with hosts that support anonymous (unauthenticated) connections.

ftpobj = ftp(host,username,password) accesses the FTP account with the specified user name and password.

ftpobj = ftp(host,username,password,Name,Value) specifies additional input arguments using one or more name-value arguments. For example, specify "System","Windows" to connect to an FTP server that runs a Windows® operating system, or specify the value of "LocalDataConnectionMethod" to change the connection mode from passive to active mode.

Input Arguments

expand all

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.

Example: ftpobj = ftp("ftp.example.com")

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 for an authorized account, specified as a string scalar or character vector. The FTP object sends password as plain text.

Example: ftpobj = ftp("ftp.example.com","myusername","mypassword")

Name-Value Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: "System","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.

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.

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 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 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:

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

  2. 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});
Pre-allocate the struct:
listing = struct("name",cell(structSize,1),"isdir",zeros(1,1), ...
        "bytes",zeros(1,1),"date",'',"datenum",zeros(1,1));
Get the individual parts from the textscan output:
monthName = string(out{3});
    day = string(out{4});
    time = string(out{5});
    names = out{1};
    bytes = out{2};
Construct the struct populating the appropriate fields:
    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

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.

Object Functions

asciiSet FTP transfer mode to ASCII
binarySet FTP transfer mode to binary
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

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: "/"

List the contents of the top-level folder on the FTP server.

dir(ftpobj)
 
DMSP                         Solid_Earth                  google12c4c939d7b90761.html  pub                          
INDEX.txt                    coastwatch                   index.html                   wdc                          
README.txt                   dmsp4alan                    international                                             
STP                          ftp.html                     ionosonde                                                 
Snow_Ice                     geomag                       mgg                                                       
 

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                   NOAA                        Solid_Earth                 publications                
DMSP                        SEIS                        aavso_22nov16               satellite_data              
ECLIPSE                     SGD                         aeronomy                    space-weather               
GEOMAGNETIC_DATA            SOLAR_DATA                  cdroms                      space_environment_modeling  
GOIN                        SPIDR                       goesr                       swpc_products               
GPS_GNSS                    STEP                        ionosonde                   tivoli                      
IONOSPHERE                  SWA                         log.txt                                                 
 

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           documentation            interplanetary-data      online-publications      solar-data               
denig-files              geomagnetic-data         ionospheric-data         satellite-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.

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: "/"

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 the cd function to navigate to the login folder.

Introduced before R2006a