1. Perl
  2. Module
  3. here

Net::FTP - File transfer using FTP

Net::FTP allows you to download and upload files via FTP.

IT-related work often accesses servers to download and upload files. Doing this using FTP client software such as FFFTP can be very tedious. You'll want to automate it if you can.

Perl comes standard with a module called Net::FTP for creating client applications for FTP. If you use Net::FTP, file download/upload work can be automated and work efficiency can be improved.

What is FTP?

FTP is a protocol for transferring files. You can use FTP to upload and download files. A little more explanation of FTP is "56th FTP (1) Overview (3 minutes Networking I think it is easy to understand.

Here, we will briefly explain the procedure for connecting to an FTP server and downloading files without detailed explanation. There are three steps to connect to an FTP server and download a file.

  1. Connect to the FTP server by specifying the host name (or IP address).
  2. Enter your username and password to log in
  3. Download the file using the FTP command
  4. Close the connection

A simple example to download a file

Let's write a simple example to actually download the file.

# Load module
use Net::FTP;

# Connect to FTP server (host name or IP address is OK)
my $ftp = Net::FTP->new('somehost');

# Login by specifying user name and password
$ftp->login('user', 'password');

# Download the file using the command get to get the file
$ftp->get('/ dir/somefile');

# Exit the connection
$ftp->quit;

You can connect to the FTP server by specifying the connection destination in the new method. In addition, an object is returned as the return value, and this is used to log in or issue an FTP command.

You can log in to the FTP server by specifying the user name and password in the login method. To put it simply, login is a state in which the server has given permission to execute FTP commands.

You can download the file using a method called get. The file will be downloaded to the current directory. The file name will be the last name (somefile in this example), not including the directory name.

Frequently used methods

Here are some commonly used methods.

new

Create a Net::FTP object to connect to the FTP server.

$ftp = Net::FTP->new($host);

You can specify the host name or IP address as an argument. In addition, options can be specified after the second argument. Options are specified in the hash reference. Frequently used options include Timeout to set the number of seconds to time out. The default timeout period is 120 seconds.

$ftp = Net::FTP->new($host, Timeout => 180)

login

Log in by specifying the user name and password.

$ftp->login($user, $password)

If you want to connect to the FTP server anonymously, specify "anonymous" as the user name.

$ftp->login('anonymous')

cwd

Change the current directory of the connection destination.

$ftp->cwd($dir)

FTP is a stateful protocol that allows you to change the destination directory. When downloading a file, it may be common to change the current directory and then specify only the file name.

# $ftp->cwd('dir') change current directory
# $ftp->get('somefile') Download file

get

Use get to download the file.

$ftp->get($file)

If you specify the file name in the second argument, you can change the name and download.

$ftp->get($file, $renamed_file)

put

Use put to upload the file.

$ftp->put($file $)

If you specify the file name in the second argument, you can change the name and upload.

$ftp->put($file, $renamed_file)

binary

Change the file transfer mode to binary mode.

$ftp->binary

FTP has the idea of a file transfer mode. There are two transfer modes, binary mode and ASCII mode.

Binary mode does not perform any conversion when transferring files. When transferring image files, video files, etc., it is necessary to transfer in binary mode.

ascii

Change the file transfer mode to ASCII mode.

$ftp->ascii

If you specify ASCII mode, the line feed code will be converted automatically. For example, the default line feed code for Windows is\r\n. The default line feed code for Unix is \n. If you transfer a file created with Windows Notepad to Unix as it is, it cannot be displayed correctly. If you transfer in ASCII mode, this conversion will be done automatically.

ls

Get a list of file names.

@files = $ftp->ls($dir)

If the directory name is omitted, the list of files included in the current directory of the connection destination is got.

To check the existence of a file, use the ls method to get a list of files and check.

dir

Get a list of file names, including detailed information.

@file_infos = $ftp->dir($dir)

The dir command is OS dependent. You can get the output result by executing "ls -l" on that OS. For example, in the case of Fedora 7 that I am currently using, the output is as follows.

-rw-r- r-- 1 someuser somegroup 6618 Aug 8 17:22 button.html
-rwxr-xr-x 3 someuser somegroup 512 Apr 1 2009 a.pl
-rwx- -- - 1 someuser somegroup 77 Apr 1 2009 mm.txt

rmdir

Delete the directory.

# Delete directory
$ftp->rmdir($dir)

mkdir

Create a directory. If the second argument is true, the directory will be created recursively.

# Create directory
$ftp->mkdir($dir)

# Recursively create directories
$ftp->mkdir($dir, $is_recurse)

quit

Close the connection with the FTP server.

$ftp->quit;

Sometimes used method

This method is used from time to time.

Method name function
pwd Get the current directory of the connection destination
rename File name change
mkdir Creating a directory
rmdir Delete directory
size Get file size

List of all methods

See the Net::FTP documentation for a complete list of methods.

Net::FTP (perldocjp)

Net::FTP error handling

In fact, the first example omitted error handling to briefly explain how to use Net::FTP. Net::FTP does not throw an exception when a command fails, so you need to handle the error yourself. Adding error handling to the first example gives:

# Connect to FTP server
my $ftp = Net::FTP->new('somehost')
  or die "Cannot connect to'$host':$!";

# Login
$ftp->login('user', 'password')
  or die "Cannot login'$host: $user: $password':". $ftp->message;

# Download
$ftp->get('/ dir/somefile');
  or die "FTP command fail:". $ftp->message;

$ftp->quit;

Why should error handling be done? Because the FTP server is external and there is no guarantee that it will succeed. You need to think about when you can't connect due to a network error or a server down.

If the host name is incorrect, the connection will fail. In such a case, there is no point in continuing the rest of the processing. The program should stop with a descriptive error message.

Let's take a brief look at Net::FTP error handling.

[A] Connection error handling

If the connection to the FTP server fails with the new method, the return value will be undef, so do or die to terminate the program. Include the OS error message $!.

my $ftp = Net::FTP->new('somehost')
  or die "Cannot connect to'$host':$!";

[B] Other error handling

If an error occurs after connecting, you can get the details of the error with $ftp->message. Make sure to include this error message in the error message.

# Login
$ftp->login('user', 'password')
  or die "Cannot login'$host: $user: $password:'". $ftp->message;

# Download
$ftp->get('/ dir/somefile');
  or die "FTP command fail:". $ftp->message;

Net::FTP executable example

The example cannot connect to the FTP server that specifies the user and password. Try downloading the file from an anonymous server that does not require a password. This is an example to download the CPAN top page (index.html) from the CPAN mirror site.

use strict;
use warnings;

use Net::FTP;

my $host = 'ftp.u-aizu.ac.jp';
my $user = 'anonymous';

my $ftp = Net::FTP->new($host)
  or die "Cannot connect to'$host':$!";

$ftp->login($user)
  or die "Cannot login'$host: $user':". $ftp->message;

$ftp->cwd('/ pub/CPAN')
  or die "FTP command fail:". $ftp->message;

$ftp->get('index.html')
  or die "FTP command fail:". $ftp->message;

$ftp->quit;

FTPS connection - FTP over SSL/TLS

I will explain how to connect with FTPS by Net::FTP. FTPS is a protocol for FTP connection over SSL/TSL. Please note that it is different from SFTP, which transfers files over SSH.

This section describes how to perform "explicit TSL/SSL encryption" that makes an SSL connection request with the AUTH command after making an FTP connection with the FTP port number (21 as standard).

Net::FTP can communicate using FTPS if IO::Socket::SSL is installed. If you have an older version of IO::Socket::SSL, please upgrade.

To do "explicit TSL/SSL encryption", just call the starttls method immediately after connecting with the new method. Let's rewrite the above example with "explicit TSL/SSL encryption".

use strict;
use warnings;

use Net::FTP;

my $host = 'ftp.u-aizu.ac.jp';
my $user = 'anonymous';

my $ftp = Net::FTP->new($host)
  or die "Cannot connect to'$host':$!";

# Start explicit TSL/SSL encryption
$ftp->starttls() or die "Can't upgrade start TLS:";

$ftp->login($user)
  or die "Cannot login'$host: $user':". $ftp->message;

$ftp->cwd('/ pub/CPAN')
  or die "FTP command fail:". $ftp->message;

$ftp->get('index.html')
  or die "FTP command fail:". $ftp->message;

$ftp->quit;

Related Informatrion