FTP

From Rosetta Code
Task
FTP
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.

Batch File[edit]

This uses the native FTP.EXE in Windows. I am not sure, but I think FTP.EXE client does not support passive mode.

::Playing with FTP
::Batch File Implementation
 
@echo off
 
set site="ftp.hq.nasa.gov"
set user="anonymous"
set pass="ftptest@example.com"
set dir="pub/issoutreach/Living in Space Stories (MP3 Files)"
set download="Gravity in the Brain.mp3"
 
(
echo.open %site%
echo.user %user% %pass%
echo.dir
echo.!echo.
echo.!echo.This is a just a text to seperate two directory listings.
echo.!echo.
echo.cd %dir%
echo.dir
echo.binary
echo.get %download%
echo.disconnect
)|ftp -n
Output:
\Desktop>RCFTP
-rw-r--r--   1 ftpadmin ftp-adm      3997 May 26  1998 README
drwxrwx-wx   6 lgipson  armd       696320 Jan 23  2015 armd
drwxrwx-wx   2 chmgt    ftp-adm      4096 Aug 18 16:17 chmgt
-r-xr-xr-x   1 root     root        18120 Nov 28  2001 ftp-exec
drwxrws-wx   2 ftpadmin ftp-adm     57344 Aug 18 13:08 incoming
-rw-rw-r--   1 ftpadmin ftp-adm       133 Jan 29  1996 index.html
drwx------   2 root     root         4096 Apr 11  2003 lost+found
drwxr-sr-x   2 ftpadmin ftp-adm      4096 Apr 14  1998 office
drwxrwsr-x  17 ftpadmin ftp-adm      4096 Nov  4  2013 pub
-rw-r--r--   1 root     ftp-adm        26 Jan 27  2011 robots.txt

This is a just a text to seperate two directory listings.

-rw-rw-r--   1 109      space-station  2327118 May  9  2005 09sept_spacepropulsion.mp3
-rw-rw-r--   1 109      space-station  1260304 May  9  2005 Can People go to Mars.mp3
-rw-rw-r--   1 109      space-station  1350270 May  9  2005 Distill some water.mp3
-rw-rw-r--   1 109      space-station  1290888 May  9  2005 Good Vibrations.mp3
-rw-rw-r--   1 109      space-station  1431834 May  9  2005 Gravity Hurts_So good.mp3
-rw-rw-r--   1 109      space-station  1072644 May  9  2005 Gravity in the Brain.mp3
-rw-rw-r--   1 109      space-station  1230594 May  9  2005 Power to the ISS.mp3
-rw-rw-r--   1 109      space-station  1309062 May  9  2005 Space Bones.mp3
-rw-rw-r--   1 109      space-station  2292715 May  9  2005 Space Power.mp3
-rw-rw-r--   1 109      space-station   772075 May  9  2005 We have a solution.mp3
-rw-rw-r--   1 109      space-station  1134654 May  9  2005 When Space Makes you Dizzy.mp3

\Desktop>

C[edit]

Using ftplib

 
#include <ftplib.h>
 
int main(void)
{
netbuf *nbuf;
 
FtpInit();
FtpConnect("kernel.org", &nbuf);
FtpLogin("anonymous", "", nbuf);
FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);
FtpChdir("pub/linux/kernel", nbuf);
FtpDir((void*)0, ".", nbuf);
FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf);
FtpQuit(nbuf);
 
return 0;
}
 

Common Lisp[edit]

Using package cl-ftp.

(use-package :ftp)
 
(with-ftp-connection (conn :hostname "ftp.hq.nasa.gov"
:passive-ftp-p t)
(send-cwd-command conn "/pub/issoutreach/Living in Space Stories (MP3 Files)")
(send-list-command conn t)
(let ((filename "Gravity in the Brain.mp3"))
(retrieve-file conn filename filename :type :binary)))
 
Output:
-rw-rw-r--   1 109      space-station  2327118 May  9  2005 09sept_spacepropulsion.mp3
-rw-rw-r--   1 109      space-station  1260304 May  9  2005 Can People go to Mars.mp3
-rw-rw-r--   1 109      space-station  1350270 May  9  2005 Distill some water.mp3
-rw-rw-r--   1 109      space-station  1290888 May  9  2005 Good Vibrations.mp3
-rw-rw-r--   1 109      space-station  1431834 May  9  2005 Gravity Hurts_So good.mp3
-rw-rw-r--   1 109      space-station  1072644 May  9  2005 Gravity in the Brain.mp3
-rw-rw-r--   1 109      space-station  1230594 May  9  2005 Power to the ISS.mp3
-rw-rw-r--   1 109      space-station  1309062 May  9  2005 Space Bones.mp3
-rw-rw-r--   1 109      space-station  2292715 May  9  2005 Space Power.mp3
-rw-rw-r--   1 109      space-station   772075 May  9  2005 We have a solution.mp3
-rw-rw-r--   1 109      space-station  1134654 May  9  2005 When Space Makes you Dizzy.mp3

Go[edit]

Using the FTP package from github.com/stacktic/ftp.

package main
 
import (
"fmt"
"io"
"log"
"os"
 
"github.com/stacktic/ftp"
)
 
func main() {
// Hard-coded demonstration values
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
 
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Quit()
fmt.Println(conn)
 
if err = conn.Login(username, password); err != nil {
log.Fatal(err)
}
if err = conn.ChangeDir(dir); err != nil {
log.Fatal(err)
}
fmt.Println(conn.CurrentDir())
files, err := conn.List(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
}
 
r, err := conn.Retr(file)
if err != nil {
log.Fatal(err)
}
defer r.Close()
 
f, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
 
n, err := io.Copy(f, r)
if err != nil {
log.Fatal(err)
}
 
fmt.Println("Wrote", n, "bytes to", file)
}

Groovy[edit]

This is the code from Ran488 GitHub, modified to be executable. It relies on external Apache FTP client. Dependencies are automatically loaded with the @Grab annotation. let's say the code is saved in the file ftpTest.groovy:

 
@Grab(group='commons-net', module='commons-net', version='2.0')
import org.apache.commons.net.ftp.FTPClient
 
println("About to connect....");
new FTPClient().with {
connect "ftp.easynet.fr"
enterLocalPassiveMode()
login "anonymous", "[email protected]"
changeWorkingDirectory "/debian/"
def incomingFile = new File("README.html")
incomingFile.withOutputStream { ostream -> retrieveFile "README.html", ostream }
disconnect()
}
println(" ...Done.");
 

By typing groovy ftpTest.groovy, you should see a README.html file on your directory.

Debian Archive

See http://www.debian.org/ for information about Debian GNU/Linux.

Current Releases

Four Debian releases are available on the main site:

Debian 6.0.10, or squeeze
Debian 6.0.10 was released Saturday, 19th July 2014. Please note that the 6.0 distribution is no longer receiving security support. If you are using the amd64 or i386 architecture and not able to upgrade to the current stable release, you may wish to investigate the "squeeze-lts" distribution. Installation and upgrading instructions, More information
....
...

J[edit]

   require 'web/gethttp'
gethttp 'ftp://anonymous:[email protected]/pub/issoutreach/Living%20in%20Space%20Stories%20(MP3%20Files)/'
-rw-rw-r-- 1 109 space-station 2327118 May 9 2005 09sept_spacepropulsion.mp3
-rw-rw-r-- 1 109 space-station 1260304 May 9 2005 Can People go to Mars.mp3
-rw-rw-r-- 1 109 space-station 1350270 May 9 2005 Distill some water.mp3
-rw-rw-r-- 1 109 space-station 1290888 May 9 2005 Good Vibrations.mp3
-rw-rw-r-- 1 109 space-station 1431834 May 9 2005 Gravity Hurts_So good.mp3
-rw-rw-r-- 1 109 space-station 1072644 May 9 2005 Gravity in the Brain.mp3
-rw-rw-r-- 1 109 space-station 1230594 May 9 2005 Power to the ISS.mp3
-rw-rw-r-- 1 109 space-station 1309062 May 9 2005 Space Bones.mp3
-rw-rw-r-- 1 109 space-station 2292715 May 9 2005 Space Power.mp3
-rw-rw-r-- 1 109 space-station 772075 May 9 2005 We have a solution.mp3
-rw-rw-r-- 1 109 space-station 1134654 May 9 2005 When Space Makes you Dizzy.mp3
#file=: gethttp rplc&(' ';'%20') 'ftp://anonymous:[email protected]/pub/issoutreach/Living in Space Stories (MP3 Files)/We have a solution.mp3'
772075

Java[edit]

requires apache.commons.net

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
 
public class FTPconn {
 
public static void main(String[] args) throws IOException {
String server = "ftp.hq.nasa.gov";
int port = 21;
String user = "anonymous";
String pass = "[email protected]";
 
OutputStream output = null;
 
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
 
serverReply(ftpClient);
 
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Failure. Server reply code: " + replyCode);
return;
}
 
serverReply(ftpClient);
 
if (!ftpClient.login(user, pass)) {
System.out.println("Could not login to the server.");
return;
}
 
String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/";
if (!ftpClient.changeWorkingDirectory(dir)) {
System.out.println("Change directory failed.");
return;
}
 
ftpClient.enterLocalPassiveMode();
 
for (FTPFile file : ftpClient.listFiles())
System.out.println(file);
 
String filename = "Can People go to Mars.mp3";
output = new FileOutputStream(filename);
 
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (!ftpClient.retrieveFile(filename, output)) {
System.out.println("Retrieving file failed");
return;
}
 
serverReply(ftpClient);
 
ftpClient.logout();
 
} finally {
if (output != null)
output.close();
}
}
 
private static void serverReply(FTPClient ftpClient) {
for (String reply : ftpClient.getReplyStrings()) {
System.out.println(reply);
}
}
}

Output:

220-Warning: This system is owned and operated by the US Federal Government.
          Unauthorized access to this system is a violation of US Federal
          law and could lead to prosecution.
 
 This is NASA HQ ANONYMOUS FTP SERVER.
 
 Please read the README file located in the initial server root directory.
 
 IF you place files into the /incoming directory, it is IMPERATIVE that you
 notify [email protected] that you have done so and of your intended
 disposition of those files.  Absent such notification, all files placed
 in /incoming that cannot be identified will be immediately deleted.
 
220 FTP Server Ready
220-Warning: This system is owned and operated by the US Federal Government.
          Unauthorized access to this system is a violation of US Federal
          law and could lead to prosecution.
 
 This is NASA HQ ANONYMOUS FTP SERVER.
 
 Please read the README file located in the initial server root directory.
 
 IF you place files into the /incoming directory, it is IMPERATIVE that you
 notify [email protected] that you have done so and of your intended
 disposition of those files.  Absent such notification, all files placed
 in /incoming that cannot be identified will be immediately deleted.
 
220 FTP Server Ready
-rw-rw-r--   1 109      space-station  2327118 May  9  2005 09sept_spacepropulsion.mp3
-rw-rw-r--   1 109      space-station  1260304 May  9  2005 Can People go to Mars.mp3
-rw-rw-r--   1 109      space-station  1350270 May  9  2005 Distill some water.mp3
-rw-rw-r--   1 109      space-station  1290888 May  9  2005 Good Vibrations.mp3
-rw-rw-r--   1 109      space-station  1431834 May  9  2005 Gravity Hurts_So good.mp3
-rw-rw-r--   1 109      space-station  1072644 May  9  2005 Gravity in the Brain.mp3
-rw-rw-r--   1 109      space-station  1230594 May  9  2005 Power to the ISS.mp3
-rw-rw-r--   1 109      space-station  1309062 May  9  2005 Space Bones.mp3
-rw-rw-r--   1 109      space-station  2292715 May  9  2005 Space Power.mp3
-rw-rw-r--   1 109      space-station   772075 May  9  2005 We have a solution.mp3
-rw-rw-r--   1 109      space-station  1134654 May  9  2005 When Space Makes you Dizzy.mp3
226 Transfer complete

Lingo[edit]

Library: Curl Xtra
CURLOPT_URL = 10002
ch = xtra("Curl").new()
url = "ftp://domain.com"
 
-- change to remote dir "/foo/bar/"
put "/foo/bar/" after url
 
ch.setOption(CURLOPT_URL, url)
res = ch.exec(1)
 
-- print raw FTP listing as string
put res.readRawString(res.length)
 
-- download file "download.mp3" (passive mode is the internal default behavior)
filename = "download.mp3"
ch.setOption(CURLOPT_URL, url & filename)
ch.setDestinationFile(_movie.path & filename)
res = ch.exec()

LiveCode[edit]

libURLSetFTPMode "passive"  --default is passive anyway
put url "ftp://ftp.hq.nasa.gov/" into listing
repeat for each line ftpln in listing
set itemdel to space
if the first char of (the first item of ftpln) is "d" then
-- is a directory
put the last item of ftpln after dirlist
else
put the last item of ftpln after filelist
end if
end repeat
 
put listing //(subset)
// -rw-r--r-- 1 ftpadmin ftp-adm 3997 May 26 1998 README
// drwxrwsr-x 17 ftpadmin ftp-adm 4096 Sep 10 16:08 pub
 
put dirlist
// armd
// chmgt
// incoming
// lost+found
// office
// pub
 
put filelist
// README
// ftp-exec
// index.html
// robots.txt
 
-- downloading a file (upload is same, but use put)
-- you don't have to cd manually
-- file up/down transfer is binary in livecode (always enforced by livecode)
put URL "ftp://ftp.hq.nasa.gov/pub/robots.txt" into URL "file:myFile.txt"
 
You can execute any ftp command using the libURLftpCommand command
e.g. to know the working directory, issue "pwd", we could issue "list" for above too,
but using an url with slash on the end with the ftp protocol causes a dir listing by default.
put libURLftpCommand("PWD",ftp.example.org)

Perl[edit]

 
#!/usr/bin/perl
use strict;
use warnings;
use 5.020;
#This script is dependent upon the Net::FTP cpan module
use Net::FTP;
 
#Put the name of the FTP server here
my $host = "kernel.org";
#Credentials go here
my $user = "anonymous";
my $password = "";
 
#Attempt to connect to the server using the credentials provided.
my $f = Net::FTP->new($host) or die("Something went wrong. Can't open $host\n");
$f->login($user, $password) or die("Something went wrong. Can't log $user in.\n");
 
#Set to passive mode
$f->passive();
 
#Change to whatever directory you want. If no args are passed to cwd(), it sets it to the root directory
$f->cwd("pub/linux/kernel");
#Print the current dir
my @dir = $f->ls();
foreach my $element (@dir)
{
say("$element");
}
 
#Download the file and store locally. get() returns the local filename
my $local = $f->get("README");
say("Your file was stored as $local in the current directory! ");
 

Output:

COPYING
CREDITS
Historic
README
SillySounds
crypto
next
people
ports
projects
sha256sums.asc
testing
uemacs
v1.0
v1.1
v1.2
v1.3
v2.0
v2.1
v2.2
v2.3
v2.4
v2.5
v2.6
v3.0
v3.x
v4.x
Your file was stored as README in the current directory! 

Perl 6[edit]

Works with: rakudo version 2015-11-02
use Net::FTP;
 
my $host = 'kernel.org';
my $user = 'anonymous';
my $password = '';
 
my $ftp = Net::FTP.new( host => $host, :passive );
 
$ftp.login( user => $user, pass => $password );
 
$ftp.cwd( 'pub/linux/kernel' );
 
say $_<name> for $ftp.ls;
 
$ftp.get( 'README', :binary );
Output:
COPYING
CREDITS
Historic
README
SillySounds
crypto
next
people
ports
projects
sha256sums.asc
testing
uemacs
v1.0
v1.1
v1.2
v1.3
v2.0
v2.1
v2.2
v2.3
v2.4
v2.5
v2.6
「v3.0」
v3.x
v4.x

PicoLisp[edit]

Passive is the default behavior of 'curl'

(in '(curl "-sl" "ftp://kernel.org/pub/site/")
(while (line)
(prinl @) ) )
(call "curl" "-s" "-o" "sha256sums.asc" "ftp://kernel.org/pub/site/sha256sums.asc")

Output:

README
sample_mirror_script.pl
sha256sums.asc

Python[edit]

Works with: Python version 2.7.10
 
from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True) # Default since Python 2.1
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
 

Racket[edit]

Note: net/ftp in Racket uses passive mode exclusively.

 
#lang racket
(require net/ftp)
(let* ([server "kernel.org"]
[remote-dir "/pub/linux/kernel/"]
[conn (ftp-establish-connection
server
21
"anonymous"
"")])
(ftp-cd conn remote-dir)
(map
(lambda (elem) (displayln (string-join elem "\t")))
(ftp-directory-list conn "."))
(ftp-download-file conn "." "README")
(ftp-close-connection conn))
 

REBOL[edit]

 
system/schemes/ftp/passive: on
print read ftp://kernel.org/pub/linux/kernel/
write/binary %README read/binary ftp://kernel.org/pub/linux/kernel/README
 

Ruby[edit]

require 'net/ftp'
 
Net::FTP.open('ftp.ed.ac.uk', "anonymous","[email protected]" ) do |ftp|
ftp.passive = true
ftp.chdir('pub/courses')
ftp.list.each{|e| puts e}
ftp.getbinaryfile("make.notes.tar")
end

The connection is closed automatically at the end of the block.

Seed7[edit]

The library ftp.s7i contains functions to open and handle an ftpFileSys.

$ include "seed7_05.s7i";
include "ftp.s7i";
 
const proc: main is func
local
var ftpFileSys: ftp is fileSys.value;
var string: line is "";
begin
ftp := openFtp("kernel.org");
setActiveMode(ftp, FALSE); # Passive is the default.
chdir(ftp, "/pub/linux/kernel");
for line range listDir(ftp, ".") do
writeln(line);
end for;
setAsciiTransfer(ftp, FALSE);
writeln(getFile(ftp, "README"));
close(ftp);
end func;

Sidef[edit]

Translation of: Ruby
require('Net::FTP');
 
var ftp = %s'Net::FTP'.new('ftp.ed.ac.uk', Passive => 1);
ftp.login('anonymous',[email protected]');
ftp.cwd('pub/courses');
[ftp.dir].each {|line| say line };
ftp.binary; # set binary mode
ftp.get("make.notes.tar");
ftp.quit;

Tcl[edit]

Using package ftp[edit]

 
package require ftp
 
set conn [::ftp::Open kernel.org anonymous "" -mode passive]
::ftp::Cd $conn /pub/linux/kernel
foreach line [ftp::NList $conn] {
puts $line
}
::ftp::Type $conn binary
::ftp::Get $conn README README
 

Using a virtual file system[edit]

An alternative approach that uses the package TclVFS to access ftp:// paths as a virtual file system.

 
package require vfs::urltype
vfs::urltype::Mount ftp
 
# Patch to enable FTP passive mode.
source vfsftpfix.tcl
 
set dir [pwd]
cd ftp://kernel.org/pub/linux/kernel
foreach line [glob -dir ftp://kernel.org/pub/linux/kernel *] {
puts $line
}
file copy README [file join $dir README]
 

The file vfsftpfix.tcl with the passive mode patch (see http://wiki.tcl.tk/12837):

 
# Replace vfs::ftp::Mount to enable vfs::ftp to work in passive
# mode and make that the default.
package require vfs::ftp
proc vfs::ftp::Mount {dirurl local {mode passive}} {
set dirurl [string trim $dirurl]
 ::vfs::log "ftp-vfs: attempt to mount $dirurl at $local"
if {[string index $dirurl end] != "/"} {
 ::vfs::log "ftp-vfs: adding missing directory delimiter to mount point"
append dirurl "/"
}
 
set urlRE {(?:ftp://)?(?:([^@:]*)(?::([^@]*))?@)?([^/:]+)(?::([0-9]*))?/(.*/)?$}
if {![regexp $urlRE $dirurl - user pass host port path]} {
return -code error "Sorry I didn't understand\
the url address \"$dirurl\""

}
 
if {![string length $user]} {
set user anonymous
}
 
if {![string length $port]} {
set port 21
}
 
set fd [::ftp::Open $host $user $pass -port $port -output ::vfs::ftp::log -mode $mode]
if {$fd == -1} {
error "Mount failed"
}
 
if {$path != ""} {
if {[catch {
 ::ftp::Cd $fd $path
} err]} {
ftp::Close $fd
error "Opened ftp connection, but then received error: $err"
}
}
 
if {![catch {vfs::filesystem info $dirurl}]} {
# unmount old mount
 ::vfs::log "ftp-vfs: unmounted old mount point at $dirurl"
vfs::unmount $dirurl
}
 ::vfs::log "ftp $host, $path mounted at $fd"
vfs::filesystem mount $local [list vfs::ftp::handler $fd $path]
# Register command to unmount
vfs::RegisterMount $local [list ::vfs::ftp::Unmount $fd]
return $fd
}
 

zkl[edit]

Using the cURL library, doing this from the REPL. Moving around in the tree isn't supported.

zkl: var cURL=Import("zklCurl")
zkl: var d=cURL().get("ftp.hq.nasa.gov/pub/issoutreach/Living in Space Stories (MP3 Files)/")
L(Data(2,567),1630,23) // downloaded listing, 1630 bytes of header, 23 bytes of trailer
zkl: d[0][1630,-23].text
-rw-rw-r-- 1 109 space-station 2327118 May 9 2005 09sept_spacepropulsion.mp3
...
-rw-rw-r-- 1 109 space-station 1134654 May 9 2005 When Space Makes you Dizzy.mp3
 
zkl: d=cURL().get("ftp.hq.nasa.gov/pub/issoutreach/Living in Space Stories (MP3 Files)/When Space Makes you Dizzy.mp3")
L(Data(1,136,358),1681,23)
zkl: File("foo.mp3","w").write(d[0][1681,-23])
1134654 // note that this matches size in listing

The resulting file foo.mp3 has a nice six minute description of what can happen when returning from space.