FTP: Difference between revisions

From Rosetta Code
Content added Content deleted
(J)
m (Convert this a "full task"... Feel free to put this bak to draft task if it needs to.)
Line 1: Line 1:
{{draft task|Programming environment operations}}[[Category:Networking and Web Interaction]]
{{task|Programming environment operations}}[[Category:Networking and Web Interaction]]


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

Revision as of 11:03, 22 August 2015

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

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

This uses the native FTP.EXE in Windows. I am not sure, but I think FTP.EXE client does not support passive mode. <lang dos>::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</lang>

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

Using ftplib <lang c>

  1. 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;

} </lang>

Go

Using the FTP package from github.com/stacktic/ftp. <lang go>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) }</lang>

J

<lang J> require 'web/gethttp'

  gethttp 'ftp://anonymous:example@ftp.hq.nasa.gov/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:example@ftp.hq.nasa.gov/pub/issoutreach/Living in Space Stories (MP3 Files)/We have a solution.mp3'

772075</lang>

Java

requires apache.commons.net <lang java>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 = "ftptest@example.com";
       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);
       }
   }

}</lang>

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 ftp-admin@hq.nasa.gov 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 ftp-admin@hq.nasa.gov 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

Python

Works with: Python version 2.7.10

<lang Python> 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() </lang>

Racket

Note: net/ftp in Racket uses passive mode exclusively. <lang racket>

  1. 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))

</lang>

REBOL

<lang REBOL> 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 </lang>

Ruby

<lang ruby>require 'net/ftp'

Net::FTP.open('ftp.ed.ac.uk', "anonymous","aaa@gmail.com" ) do |ftp|

 ftp.passive = true
 ftp.chdir('pub/courses')
 ftp.list.each{|e| puts e}
 ftp.getbinaryfile("make.notes.tar")

end</lang> The connection is closed automatically at the end of the block.

Tcl

Using package ftp

<lang Tcl> 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

</lang>

Using a virtual file system

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

<lang tcl> package require vfs::urltype vfs::urltype::Mount ftp

  1. 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] </lang>

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

  1. Replace vfs::ftp::Mount to enable vfs::ftp to work in passive
  2. 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

} </lang>

zkl

Using the cURL library, doing this from the REPL. Moving around in the tree isn't supported. <lang zkl>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</lang> The resulting file foo.mp3 has a nice six minute description of what can happen when returning from space.