ftp - Connection to FTP server to access its files - MATLAB (original) (raw)

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([host](#d126e602877)) 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.

example

ftpobj = ftp([host](#d126e602877),[username](#d126e602928)) 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](#d126e602877),[username](#d126e602928),[password](#d126e602950)) accesses the FTP account with the specified user name and password.

ftpobj = ftp([host](#d126e602877),[username](#d126e602928),[password](#d126e602950),[Name,Value](#namevaluepairarguments)) specifies options using one or more name-value arguments. For example, you can specify "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

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 withftp, 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 serverwww.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")

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

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

Name-Value Arguments

expand all

Specify optional pairs of arguments asName1=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")

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 specifyactive mode.

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:

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

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, anddatenum. 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.

Since R2024b

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

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.

Since R2024b

Connection to the server using TLS/SSL, specified as one of these values:

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, specifyTLSMode 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

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: "/"
      CertificateFilename: "default"
        ConnectionTimeout: 5 min
          TransferTimeout: Inf sec

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

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.

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.

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.

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

Version History

Introduced before R2006a

expand all

You can specify the maximum amount of time allowed for a connection and for a transfer by using the ConnectionTimeout andTransferTimeout name-value arguments, respectively.

When you connect to an FTP server, you can enable Transport Layer Security (TLS) using the TLSMode name-value argument.