Important alert: (current site time 7/15/2013 8:34:29 PM EDT)
 

article

Coding ftp in perl by Rohit D'souza BrandCoder

Email
Submitted on: 5/23/2008 1:08:52 PM
By: rohit d'souza  
Level: Advanced
User Rating: Unrated
Compatibility: 5.0 (all versions)
Views: 13308
author picture
(About the author)
 
     its explains how to get started on ftp in perl

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				So how do we code ftp in perl.Its easy to get started read on....
Lets see what are the main methods for ftp.First of all one should have the Net:FTP package to use ftp in perl.
Below are the list and explanation of some important ftp class methods which will get us started.
CONSTRUCTOR
* new ([ HOST ] [, OPTIONS ])
This is the constructor for a new Net::FTP object. HOST is the name of the remote host to which an FTP connection is required.
HOST is optional. If HOST is not given then it may instead be passed as the Host option described below.
OPTIONS are passed in a hash like fashion, using key and value pairs. Possible options are:
Host - FTP host to connect to. It may be a single scalar, as defined for the PeerAddr option in IO::Socket::INET, or a reference to an array with hosts to try in turn. The "host" method will return the value which was used to connect to the host.
Firewall - The name of a machine which acts as an FTP firewall. This can be overridden by an environment variable FTP_FIREWALL . If specified, and the given host cannot be directly connected to, then the connection is made to the firewall machine and the string @hostname is appended to the login identifier. This kind of setup is also referred to as an ftp proxy.
FirewallType - The type of firewall running on the machine indicated by Firewall. This can be overridden by an environment variable FTP_FIREWALL_TYPE . For a list of permissible types, see the description of ftp_firewall_type in Net::Config.
BlockSize - This is the block size that Net::FTP will use when doing transfers. (defaults to 10240)
Port - The port number to connect to on the remote machine for the FTP connection
Timeout - Set a timeout value (defaults to 120)
Debug - debug level (see the debug method in Net::Cmd)
Passive - If set to a non-zero value then all data transfers will be done using passive mode. If set to zero then data transfers will be done using active mode. If the machine is connected to the Internet directly, both passive and active mode should work equally well. Behind most firewall and NAT configurations passive mode has a better chance of working. However, in some rare firewall configurations, active mode actually works when passive mode doesn't. Some really old FTP servers might not implement passive transfers. If not specified, then the transfer mode is set by the environment variable FTP_PASSIVE or if that one is not set by the settings done by the libnetcfg utility. If none of these apply then passive mode is used.
Hash - If given a reference to a file handle (e.g., \*STDERR ), print hash marks (#) on that filehandle every 1024 bytes. This simply invokes the hash() method for you, so that hash marks are displayed for all transfers. You can, of course, call hash() explicitly whenever you'd like.
LocalAddr - Local address to use for all socket connections, this argument will be passed to IO::Socket::INET
If the constructor fails undef will be returned and an error message will be in $@
METHODS
Unless otherwise stated all methods return either a true or false value, with true meaning that the operation was a success. When a method states that it returns a value, failure will be returned as undef or an empty list.
* login ([LOGIN [,PASSWORD [, ACCOUNT] ] ])
Log into the remote FTP server with the given login information. If no arguments are given then the Net::FTP uses the Net::Netrc package to lookup the login information for the connected host. If no information is found then a login of anonymous is used. If no password is given and the login is anonymous then anonymous@ will be used for password.
If the connection is via a firewall then the authorize method will be called with no arguments.
* authorize ( [AUTH [, RESP]])
This is a protocol used by some firewall ftp proxies. It is used to authorise the user to send data out. If both arguments are not specified then authorize uses Net::Netrc to do a lookup.
* site (ARGS)
Send a SITE command to the remote server and wait for a response.
Returns most significant digit of the response code.
* ascii
Transfer file in ASCII. CRLF translation will be done if required
* binary
Transfer file in binary mode. No transformation will be done.
Hint: If both server and client machines use the same line ending for text files, then it will be faster to transfer all files in binary mode.
* rename ( OLDNAME, NEWNAME )
Rename a file on the remote FTP server from OLDNAME to NEWNAME . This is done by sending the RNFR and RNTO commands.
* delete ( FILENAME )
Send a request to the server to delete FILENAME .
* cwd ( [ DIR ] )
Attempt to change directory to the directory given in $dir . If $dir is ".." , the FTP CDUP command is used to attempt to move up one directory. If no directory is given then an attempt is made to change the directory to the root directory.
* cdup ()
Change directory to the parent of the current directory.
* pwd ()
Returns the full pathname of the current directory.
* restart ( WHERE )
Set the byte offset at which to begin the next data transfer. Net::FTP simply records this value and uses it when during the next data transfer. For this reason this method will not return an error, but setting it may cause a subsequent data transfer to fail.
* rmdir ( DIR [, RECURSE ])
Remove the directory with the name DIR . If RECURSE is true then rmdir will attempt to delete everything inside the directory.
* mkdir ( DIR [, RECURSE ])
Create a new directory with the name DIR . If RECURSE is true then mkdir will attempt to create all the directories in the given path.
Returns the full pathname to the new directory.
* alloc ( SIZE [, RECORD_SIZE] )
The alloc command allows you to give the ftp server a hint about the size of the file about to be transferred using the ALLO ftp command. Some storage systems use this to make intelligent decisions about how to store the file. The SIZE argument represents the size of the file in bytes. The RECORD_SIZE argument indicates a maximum record or page size for files sent with a record or page structure.
The size of the file will be determined, and sent to the server automatically for normal files so that this method need only be called if you are transferring data from a socket, named pipe, or other stream not associated with a normal file.
* ls ( [ DIR ] )
Get a directory listing of DIR , or the current directory.
In an array context, returns a list of lines returned from the server. In a scalar context, returns a reference to a list.
* dir ( [ DIR ] )
Get a directory listing of DIR , or the current directory in long format.
In an array context, returns a list of lines returned from the server. In a scalar context, returns a reference to a list.
* get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] )
Get REMOTE_FILE from the server and store locally. LOCAL_FILE may be a filename or a filehandle. If not specified, the file will be stored in the current directory with the same leafname as the remote file.
If WHERE is given then the first WHERE bytes of the file will not be transferred, and the remaining bytes will be appended to the local file if it already exists.
Returns LOCAL_FILE , or the generated local file name if LOCAL_FILE is not given. If an error was encountered undef is returned.
* put ( LOCAL_FILE [, REMOTE_FILE ] )
Put a file on the remote server. LOCAL_FILE may be a name or a filehandle. If LOCAL_FILE is a filehandle then REMOTE_FILE must be specified. If REMOTE_FILE is not specified then the file will be stored in the current directory with the same leafname as LOCAL_FILE .
Returns REMOTE_FILE , or the generated remote filename if REMOTE_FILE is not given.
NOTE: If for some reason the transfer does not complete and an error is returned then the contents that had been transferred will not be remove automatically.
* put_unique ( LOCAL_FILE [, REMOTE_FILE ] )
Same as put but uses the STOU command.
Returns the name of the file on the server.
* append ( LOCAL_FILE [, REMOTE_FILE ] )
Same as put but appends to the file on the remote server.
Returns REMOTE_FILE , or the generated remote filename if REMOTE_FILE is not given.
* unique_name ()
Returns the name of the last file stored on the server using the STOU command.
* mdtm ( FILE )
Returns the modification time of the given file
* size ( FILE )
Returns the size in bytes for the given file as stored on the remote server.
NOTE: The size reported is the size of the stored file on the remote server. If the file is subsequently transferred from the server in ASCII mode and the remote server and local machine have different ideas about "End Of Line" then the size of file on the local machine after transfer may be different.
* supported ( CMD )
Returns TRUE if the remote server supports the given command.
* hash ( [FILEHANDLE_GLOB_REF],[ BYTES_PER_HASH_MARK] )
Called without parameters, or with the first argument false, hash marks are suppressed. If the first argument is true but not a reference to a file handle glob, then \*STDERR is used. The second argument is the number of bytes per hash mark printed, and defaults to 1024. In all cases the return value is a reference to an array of two: the filehandle glob reference and the bytes per hash mark.
* feature ( NAME )
Determine if the server supports the specified feature. The return value is a list of lines the server responded with to describe the options that it supports for the given feature. If the feature is unsupported then the empty list is returned.
if ($ftp->feature( 'MDTM' )) {
# Do something
}
if (grep { /\bTLS\b/ } $ftp->feature('AUTH')) {
# Server supports TLS
}
The following methods can return different results depending on how they are called. If the user explicitly calls either of the pasv or port methods then these methods will return a true or false value. If the user does not call either of these methods then the result will be a reference to a Net::FTP::dataconn based object.
* nlst ( [ DIR ] )
Send an NLST command to the server, with an optional parameter.
* list ( [ DIR ] )
Same as nlst but using the LIST command
* retr ( FILE )
Begin the retrieval of a file called FILE from the remote server.
* stor ( FILE )
Tell the server that you wish to store a file. FILE is the name of the new file that should be created.
* stou ( FILE )
Same as stor but using the STOU command. The name of the unique file which was created on the server will be available via the unique_name method after the data connection has been closed.
* appe ( FILE )
Tell the server that we want to append some data to the end of a file called FILE . If this file does not exist then create it.
If for some reason you want to have complete control over the data connection, this includes generating it and calling the response method when required, then the user can use these methods to do so.
However calling these methods only affects the use of the methods above that can return a data connection. They have no effect on methods get , put , put_unique and those that do not require data connections.
* port ( [ PORT ] )
Send a PORT command to the server. If PORT is specified then it is sent to the server. If not, then a listen socket is created and the correct information sent to the server.
* pasv ()
Tell the server to go into passive mode. Returns the text that represents the port on which the server is listening, this text is in a suitable form to sent to another ftp server using the port method.
The following methods can be used to transfer files between two remote servers, providing that these two servers can connect directly to each other.
* pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
This method will do a file transfer between two remote ftp servers. If DEST_FILE is omitted then the leaf name of SRC_FILE will be used.
* pasv_xfer_unique ( SRC_FILE, DEST_SERVER [, DEST_FILE ] )
Like pasv_xfer but the file is stored on the remote server using the STOU command.
* pasv_wait ( NON_PASV_SERVER )
This method can be used to wait for a transfer to complete between a passive server and a non-passive server. The method should be called on the passive server with the Net::FTP object for the non-passive server passed as an argument.
* abort ()
Abort the current data transfer.
* quit ()
Send the QUIT command to the remote FTP server and close the socket connection.
Methods for the adventurous
Net::FTP inherits from Net::Cmd so methods defined in Net::Cmd may be used to send commands to the remote FTP server.
* quot (CMD [,ARGS])
Send a command, that Net::FTP does not directly support, to the remote server and wait for a response.
Returns most significant digit of the response code.
WARNING This call should only be used on commands that do not require data connections. Misuse of this method can hang the connection.
THE dataconn CLASS
Some of the methods defined in Net::FTP return an object which will be derived from this class.The dataconn class itself is derived from the IO::Socket::INET class, so any normal IO operations can be performed. However the following methods are defined in the dataconn class and IO should be performed using these.
* read ( BUFFER, SIZE [, TIMEOUT ] )
Read SIZE bytes of data from the server and place it into BUFFER , also performing any translation necessary. TIMEOUT is optional, if not given, the timeout value from the command connection will be used.
Returns the number of bytes read before any translation.
* write ( BUFFER, SIZE [, TIMEOUT ] )
Write SIZE bytes of data from BUFFER to the server, also performing any translation necessary. TIMEOUT is optional, if not given, the timeout value from the command connection will be used.
Returns the number of bytes written before any translation.
* bytes_read ()
Returns the number of bytes read so far.
* abort ()
Abort the current data transfer.
* close ()
Close the data connection and get a response from the FTP server. Returns true if the connection was closed successfully and the first digit of the response from the server was a '2'.
UNIMPLEMENTED
The following RFC959 commands have not been implemented:
* SMNT
Mount a different file system structure without changing login or accounting information.
* HELP
Ask the server for "helpful information" (that's what the RFC says) on the commands it accepts.
* MODE
Specifies transfer mode (stream, block or compressed) for file to be transferred.
* SYST
Request remote server system identification.
* STAT
Request remote server status.
* STRU
Specifies file structure for file to be transferred.
* REIN
Reinitialize the connection, flushing all I/O and account information.
Now lets look at a simple example
#!/usr/bin/perl
use Net::FTP;##########Define the ftp class
###########this is error printing subroutine###################
sub gettheerror {
print "Error in your ftp commands are: \n";
print @ERRORS;
exit 0;
}
#first we have to define the ftp hostname and the directory to browse
my $ftphost="yourftpsite.com";
my $browsedirectory="rohitdsouza";
$ftp=Net::FTP->new($ftphost,Timeout=>350) or $gettheerror=1;#####this connects to the host or throws an error
push @ERRORS, "Can't ftp to $host: $!\n" if $gettheerror;#######we push the arrays onto a array which we will display in the error display routine
$gettheerror() if $gettheerror;
print "Connected to te ftp host $ftphost\n";
$ftp->login("rohitdsouza","password") or $gettheerror=1;########now login to the account
#If no information is found then a login of anonymous is used. If no password is given and the login is anonymous then anonymous@ will be used for password.
#If the connection is via a firewall then the authorize method will be called with no arguments.
print "Getting file list";
push @ERRORS, "Can't login to $host: $!\n" if $gettheerror;
$ftp->quit if $gettheerror;
gettheerror() if $gettheerror;
print "Logged in\n";
$ftp->cwd($browsedirectory) or $gettheerror=1; now chnage the current working directory to the desired directory
push @ERRORS, "Can't cd $!\n" if $gettheerror;
gettheerror() if $gettheerror;
$ftp->quit if $gettheerror;
@files=$ftp->dir or $gettheerror=1;# do the file listing by puuting the file names in an array
push @ERRORS, "Can't get file list $!\n" if $gettheerror;
gettheerror() if $gettheerror;
print "Got file list\n";
foreach(@files) {
print "$_\n";#######print the files here
}
$ftp->quit;
for more articles visit
http://indiascoder.blogspot.com


Other 10 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Advanced category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
11/11/2008 8:25:20 AMKelvin C. Perez - Valentin

Hi:
This sounds really good and interesting. However the formatting makes it very hard to read. Hope it can be fixed.
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.