FTP: Difference between revisions

12,150 bytes added ,  5 months ago
m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(10 intermediate revisions by 8 users not shown)
Line 5:
<br/><br/>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
Using libCURL.
<langsyntaxhighlight lang="bacon">OPTION PARSE FALSE
 
PRAGMA INCLUDE <curl/curl.h>
Line 23 ⟶ 24:
curl_easy_cleanup(easyhandle)
 
CLOSE FILE download</langsyntaxhighlight>
 
Full native implementation without dependency to external libraries.
<langsyntaxhighlight lang="bacon">FUNCTION interact$(command$, connection, use_pasv)
 
LOCAL pasv$, data$, response$
Line 71 ⟶ 72:
PRINT interact$("QUIT", ftp, 0)
 
CLOSE NETWORK ftp</langsyntaxhighlight>
 
 
==={{header|FreeBASIC}}===
Original code programmed by PaulSquires
[https://www.freebasic.net/forum/viewtopic.php?f=7&t=23867]
{{libheader|clsFTP}}
{{works with|Windows}}
====clsFTP.bas====
<syntaxhighlight lang="vb">''
''
'' FTP class (Public Domain code - enjoy).
'' Windows only. Uses WinInet system functions.
'' Paul Squires of PlanetSquires Software (August 2015)
''
'' Compiler: FreeBASIC 1.03 (32-bit) (64-bit)
''
 
#Include Once "windows.bi"
#Include Once "\win\wininet.bi"
 
' //
' //
' //
Type clsFTP
Private:
m_hSession As HINTERNET
m_hConnection As HINTERNET
m_LastError As Integer
m_ServerPort As Integer
m_ServerName As String
m_UserName As String
m_Password As String
Public:
Declare Constructor
Declare Destructor
Declare Property hSession() As HINTERNET
Declare Property hSession(Byval nValue As HINTERNET)
Declare Property hConnection() As HINTERNET
Declare Property hConnection(Byval nValue As HINTERNET)
Declare Property LastError() As Integer
Declare Property ServerPort(Byval nValue As Integer)
Declare Property ServerPort() As Integer
Declare Property LastError(Byval nValue As Integer)
Declare Property ServerName() As String
Declare Property ServerName(Byval sValue As String)
Declare Property UserName() As String
Declare Property UserName(Byval sValue As String)
Declare Property Password() As String
Declare Property Password(Byval sValue As String)
Declare Function Connect Overload() As WINBOOL
Declare Function Connect Overload(Byval sServerName As String, _
Byval sServerPort As Integer, _
Byval sUserName As String, _
Byval sPassword As String) As WINBOOL
Declare Sub Disconnect()
Declare Function SetCurrentFolder(Byval sFolderName As String) As WINBOOL
Declare Function GetCurrentFolder() As String
Declare Function RenameFile(Byval sOldFilename As String, _
Byval sNewFilename As String) As WINBOOL
Declare Function UploadFile(Byval sLocal As String, _
Byval sRemote As String) As WINBOOL
Declare Function DownloadFile(Byval sLocal As String, _
Byval sRemote As String) As WINBOOL
Declare Function KillFile(Byval sRemote As String) As WINBOOL
End Type
 
 
''
'' Initialize the class
''
Constructor clsFTP
m_ServerPort = INTERNET_DEFAULT_FTP_PORT ' port 21
End Constructor
 
 
''
'' Close any open connection and session
''
Destructor clsFTP
this.Disconnect
End Destructor
 
 
''
'' hSession (Property)
''
Property clsFTP.hSession() As HINTERNET
Property = this.m_hSession
End Property
 
Property clsFTp.hSession(Byval nValue As HINTERNET)
this.m_hSession = nValue
End Property
 
 
''
'' hConnection (Property)
''
Property clsFTP.hConnection() As HINTERNET
Property = this.m_hConnection
End Property
 
Property clsFTp.hConnection(Byval nValue As HINTERNET)
this.m_hConnection = nValue
End Property
 
 
''
'' LastError (Property)
''
Property clsFTP.LastError() As Integer
Property = this.m_LastError
End Property
 
Property clsFTp.LastError(Byval nValue As Integer)
this.m_LastError = nValue
End Property
 
 
''
'' ServerPort (Property)
''
Property clsFTP.ServerPort() As Integer
Property = this.m_ServerPort
End Property
 
Property clsFTp.ServerPort(Byval nValue As Integer)
this.m_ServerPort = nValue
End Property
 
 
''
'' ServerName (Property)
''
Property clsFTP.ServerName() As String
Property = this.m_ServerName
End Property
 
Property clsFTp.ServerName(Byval sValue As String)
this.m_ServerName = sValue
End Property
 
 
''
'' UserName (Property)
''
Property clsFTP.UserName() As String
Property = this.m_UserName
End Property
 
Property clsFTp.UserName(Byval sValue As String)
this.m_UserName = sValue
End Property
 
 
''
'' Password (Property)
''
Property clsFTP.Password() As String
Property = this.m_Password
End Property
 
Property clsFTp.Password(Byval sValue As String)
this.m_Password = sValue
End Property
 
 
''
'' Close current connection and end session
''
Sub clsFTP.Disconnect()
InternetCloseHandle this.hConnection
InternetCloseHandle this.hSession
this.hConnection = 0: this.hSession = 0
End Sub
 
 
''
'' Connect to an ftp host (overload). Returns TRUE if successful.
''
Function clsFTP.Connect Overload() As WINBOOL
this.hSession = InternetOpen("ftpClass", INTERNET_OPEN_TYPE_DIRECT, "", "", 0)
If this.hSession = 0 Then
this.LastError = GetLastError
Function = False: Exit Function
End If
this.hConnection = InternetConnect(_
this.hSession, this.ServerName, this.ServerPort, _
this.UserName, this.Password, _
INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0)
If this.hConnection = 0 Then
this.LastError = GetLastError
InternetCloseHandle(this.hSession)
Function = False: Exit Function
End If
Function = True
End Function
 
 
''
'' Connect to an ftp host (overload). Returns TRUE if successful.
''
Function clsFTP.Connect Overload (Byval sServerName As String, _
Byval nServerPort As Integer, _
Byval sUserName As String, _
Byval sPassword As String) As WINBOOL
this.ServerName = sServerName
this.ServerPort = nServerPort
this.UserName = sUserName
this.Password = sPassword
Function = this.Connect
End Function
 
 
''
'' Change to a folder on the server. Returns TRUE if successful.
''
Function clsFTP.SetCurrentFolder(Byval sFolderName As String) As WINBOOL
Function = FtpSetCurrentDirectory(this.hConnection, sFolderName)
this.LastError = GetLastError
End Function
 
 
''
'' Retrieves the name of current folder on the server.
''
Function clsFTP.GetCurrentFolder() As String
Dim zBuffer As ZString * MAX_PATH
Dim nLength As Integer = MAX_PATH
FtpGetCurrentDirectory(this.hConnection, zBuffer, Cast(LPDWORD, @nLength))
this.LastError = GetLastError
Function = zBuffer
End Function
 
 
''
'' Rename a file on the server. Returns TRUE if successful.
''
Function clsFTP.RenameFile(Byval sOldFilename As String, Byval sNewFilename As String) As WINBOOL
Function = FtpRenameFile(this.hConnection, sOldFilename, sNewFilename)
this.LastError = GetLastError
End Function
 
 
''
'' Upload a file to the server. Returns TRUE if successful.
''
Function clsFTP.UploadFile(Byval sLocal As String, Byval sRemote As String) As WINBOOL
Function = FtpPutFile(this.hConnection, sLocal, sRemote, FTP_TRANSFER_TYPE_BINARY, 0)
this.LastError = GetLastError
End Function
 
 
''
'' Download a file from the server. Returns TRUE if successful.
''
Function clsFTP.DownloadFile(Byval sLocal As String, Byval sRemote As String) As WINBOOL
Function = FtpGetFile(this.hConnection, sRemote, sLocal, False, _
FILE_ATTRIBUTE_NORMAL, FTP_TRANSFER_TYPE_BINARY Or INTERNET_FLAG_RELOAD, 0)
this.LastError = GetLastError
End Function
 
 
''
'' Remove a file from the server. Returns TRUE if successful.
''
Function clsFTP.KillFile(Byval sRemote As String) As WINBOOL
Function = FtpDeleteFile(this.hConnection, sRemote)
this.LastError = GetLastError
End Function</syntaxhighlight>
 
====simple_test.bas====
<syntaxhighlight lang="vb">#Include Once "windows.bi"
#Include Once "clsFTP.bas"
 
Dim ftp As clsFTP
 
If ftp.Connect("ftp.ed.ac.uk", 21, "anonymous", "aaa@gmail.com") = False Then
Print "Error connecting to server. LastError = "; ftp.LastError
End If
 
If ftp.SetCurrentFolder("pub/courses") = False Then
Print "Error setting current folder. LastError = "; ftp.LastError
End If
 
Print "Current folder = "; ftp.GetCurrentFolder()
 
If ftp.DownloadFile("make.notes.tar", "make.notes.tar") = False Then
Print "Error downloading file. LastError = "; ftp.LastError
End If
 
ftp.Disconnect
 
Print "Done."
 
Sleep</syntaxhighlight>
 
==={{header|FutureBasic}}===
FB for Mac easily interfaces with the terminal command line. NOTE: The curl command line tool used in this example offers upload and sending capabilities. It supports FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS, FILE, POP3, IMAP, SMTP, RTMP and RTSP.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
 
local fn RunTerminalCommand( cmd as CFStringRef ) as CFStringRef
CFStringRef outputStr = NULL
TaskRef task = fn TaskInit
TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/zsh" ) )
CFStringRef cmdStr = fn StringWithFormat( @"%@", cmd )
CFArrayRef args = fn ArrayWithObjects( @"-c", cmdStr, NULL )
TaskSetArguments( task, args )
PipeRef p = fn PipeInit
TaskSetStandardOutput( task, p )
TaskSetStandardError( task, p )
FileHandleRef fh = fn PipeFileHandleForReading( p )
fn TaskLaunch( task, NULL )
TaskWaitUntilExit( task )
ErrorRef err
CFDataRef dta = fn FileHandleReadDataToEndOfFile( fh, @err )
if err then NSLog( @"%@", fn ErrorLocalizedDescription( err ) ) : exit fn
outputStr = fn StringWithData( dta, NSUTF8StringEncoding )
end fn = outputStr
 
NSLog( @"%@", fn RunTerminalCommand( @"curl ftp://ftp.slackware.com/welcome.msg" ) )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre style="font-size: 12px">
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
 
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 754 100 754 0 0 1363 0 --:--:-- --:--:-- --:--:-- 1361
 
---------------------------------------------------------------------------
R S Y N C . O S U O S L . O R G
Oregon State University
Open Source Lab
 
Unauthorized use is prohibited - violators will be prosecuted
---------------------------------------------------------------------------
 
For more information about the OSL visit:
http://osuosl.org/services/hosting
 
This host is the home to the primary archives of several
projects. We would prefer that only primary/secondary
mirrors use this service. Thanks!
 
---------------------------------------------------------------------------
</pre>
 
=={{header|Go}}==
Using the FTP package from [https://godoc.org/github.com/stacktic/ftp github.com/stacktic/ftp].
<syntaxhighlight 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)
}</syntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="dos">::Playing with FTP
::Batch File Implementation
 
Line 98 ⟶ 529:
echo.get %download%
echo.disconnect
)|ftp -n</langsyntaxhighlight>
{{Out}}
<pre>\Desktop>RCFTP
Line 130 ⟶ 561:
=={{header|C}}==
Using [http://nbpfaus.net/~pfau/ftplib/ ftplib]
<syntaxhighlight lang="c">
<lang c>
#include <ftplib.h>
 
Line 148 ⟶ 579:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Line 154 ⟶ 585:
 
Using [http://nbpfaus.net/~pfau/ftplib/ ftplib], [https://github.com/saur0n/libftpxx libftp++]
<langsyntaxhighlight lang="cpp"> /* client.cpp
libftp++ C++ classes for ftplib C ftp library
Line 493 ⟶ 924:
}
/* END */
</syntaxhighlight>
</lang>
 
{{Out}}
Line 539 ⟶ 970:
Using package [http://code.kepibu.org/cl-ftp/ cl-ftp].
 
<langsyntaxhighlight lang="lisp">(use-package :ftp)
 
(with-ftp-connection (conn :hostname "ftp.hq.nasa.gov"
Line 547 ⟶ 978:
(let ((filename "Gravity in the Brain.mp3"))
(retrieve-file conn filename filename :type :binary)))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 565 ⟶ 996:
=={{header|Erlang}}==
Erlang implementation using ftp module.
<langsyntaxhighlight lang="erlang">
%%%-------------------------------------------------------------------
%%% To execute in shell, Run the following commands:-
Line 608 ⟶ 1,039:
io:format("Closing connection to FTP Server"),
ftp:close(Pid).
</syntaxhighlight>
</lang>
 
 
 
=={{header|FutureBasic}}==
FB for Mac easily interfaces with the terminal commandline.
<lang futurebasic>
include "NSLog.incl"
 
#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}
 
local fn RunTerminalCommand( cmd as CFStringRef ) as CFStringRef
'~'1
CFStringRef outputStr = NULL
 
TaskRef task = fn TaskInit
TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/zsh" ) )
CFStringRef cmdStr = fn StringWithFormat( @"%@", cmd )
CFArrayRef args = fn ArrayWithObjects( @"-c", cmdStr, NULL )
TaskSetArguments( task, args )
 
PipeRef p = fn PipeInit
TaskSetStandardOutput( task, p )
TaskSetStandardError( task, p )
FileHandleRef fh = fn PipeFileHandleForReading( p )
 
fn TaskLaunch( task, NULL )
TaskWaitUntilExit( task )
 
ErrorRef err
CFDataRef dta = fn FileHandleReadDataToEndOfFile( fh, @err )
if err then NSLog( @"%@", fn ErrorLocalizedDescription( err ) ) : exit fn
outputStr = fn StringWithData( dta, NSUTF8StringEncoding )
end fn = outputStr
 
NSLog( @"%@", fn RunTerminalCommand( @"curl ftp://ftp.slackware.com/welcome.msg" ) )
 
HandleEvents
</lang>
{{output}}
<pre>
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
 
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 754 100 754 0 0 1363 0 --:--:-- --:--:-- --:--:-- 1361
 
---------------------------------------------------------------------------
R S Y N C . O S U O S L . O R G
Oregon State University
Open Source Lab
 
Unauthorized use is prohibited - violators will be prosecuted
---------------------------------------------------------------------------
 
For more information about the OSL visit:
http://osuosl.org/services/hosting
 
This host is the home to the primary archives of several
projects. We would prefer that only primary/secondary
mirrors use this service. Thanks!
 
---------------------------------------------------------------------------
</pre>
 
 
 
 
 
=={{header|Go}}==
Using the FTP package from [https://godoc.org/github.com/stacktic/ftp 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>
 
 
 
=={{header|Groovy}}==
Line 750 ⟶ 1,046:
Dependencies are automatically loaded with the @Grab annotation.
let's say the code is saved in the file ftpTest.groovy:
<syntaxhighlight lang="groovy">
<lang Groovy>
@Grab(group='commons-net', module='commons-net', version='2.0')
import org.apache.commons.net.ftp.FTPClient
Line 765 ⟶ 1,061:
}
println(" ...Done.");
</syntaxhighlight>
</lang>
By typing groovy ftpTest.groovy, you should see a README.html file on your directory.
<pre>
Line 786 ⟶ 1,082:
Example uses [https://hackage.haskell.org/package/ftphs <tt>ftphs</tt>] package:
 
<langsyntaxhighlight lang="haskell">module Main (main) where
 
import Control.Exception (bracket)
Line 816 ⟶ 1,112:
-- Download in binary mode
(fileData, _) <- getbinary h "linux-0.01.tar.gz.sign"
print fileData</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="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
Line 834 ⟶ 1,130:
-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</langsyntaxhighlight>
 
=={{header|Java}}==
requires apache.commons.net
<langsyntaxhighlight lang="java">import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
Line 910 ⟶ 1,206:
}
}
}</langsyntaxhighlight>
 
Output:
Line 958 ⟶ 1,254:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using FTPClient
 
ftp = FTP(hostname = "ftp.ed.ac.uk", username = "anonymous")
Line 965 ⟶ 1,261:
bytes = read(download(ftp, "make.notes.tar"))
 
close(ftp)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Line 1,000 ⟶ 1,296:
</pre>
Next, you need to compile the following Kotlin program, linking against ftplib.klib.
<langsyntaxhighlight lang="scala">// Kotlin Native v0.6
 
import kotlinx.cinterop.*
Line 1,017 ⟶ 1,313:
FtpQuit(vnbuf)
nativeHeap.free(nbuf)
}</langsyntaxhighlight>
Finally, the resulting .kexe file should be executed producing something similar to the following output:
<pre>
Line 1,038 ⟶ 1,334:
=={{header|Lingo}}==
{{libheader|Curl Xtra}}
<langsyntaxhighlight lang="lingo">CURLOPT_URL = 10002
ch = xtra("Curl").new()
url = "ftp://domain.com"
Line 1,055 ⟶ 1,351:
ch.setOption(CURLOPT_URL, url & filename)
ch.setDestinationFile(_movie.path & filename)
res = ch.exec()</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">libURLSetFTPMode "passive" --default is passive anyway
put url "ftp://ftp.hq.nasa.gov/" into listing
repeat for each line ftpln in listing
Line 1,096 ⟶ 1,392:
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)</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 1,102 ⟶ 1,398:
{{works with|Nim|1.4}}
 
<langsyntaxhighlight lang="nim">import asyncdispatch, asyncftpclient
 
const
Line 1,131 ⟶ 1,427:
echo await ftp.send("QUIT") # Disconnect.
 
waitFor main()</langsyntaxhighlight>
 
{{out}}
Line 1,153 ⟶ 1,449:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Net::FTP;
 
# set server and credentials
Line 1,174 ⟶ 1,470:
$f->type('binary');
$local = $f->get('512KB.zip');
print "Your file was stored as $local in the current directory\n";</langsyntaxhighlight>
{{out}}
<pre>Currently 20 files in the 'upload' directory
Line 1,181 ⟶ 1,477:
=={{header|Phix}}==
{{libheader|Phix/libcurl}}
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- libcurl, allocate, file i/o</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">libcurl</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 1,206 ⟶ 1,502:
<span style="color: #0000FF;">?{</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,231 ⟶ 1,527:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
$server = "speedtest.tele2.net";
$user = "anonymous";
Line 1,252 ⟶ 1,548:
} else {
echo "failed to download file";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,283 ⟶ 1,579:
=={{header|PicoLisp}}==
Passive is the default behavior of 'curl'
<langsyntaxhighlight PicoLisplang="picolisp">(in '(curl "-sl" "ftp://kernel.org/pub/site/")
(while (line)
(prinl @) ) )
(call "curl" "-s" "-o" "sha256sums.asc" "ftp://kernel.org/pub/site/sha256sums.asc")</langsyntaxhighlight>
Output:
<pre>README
Line 1,294 ⟶ 1,590:
=={{header|Python}}==
{{works with|Python|2.7.10}}
<syntaxhighlight lang="python">
<lang Python>
from ftplib import FTP
ftp = FTP('kernel.org')
Line 1,303 ⟶ 1,599:
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Note: <tt>net/ftp</tt> in Racket uses passive mode exclusively.
<langsyntaxhighlight lang="racket">
#lang racket
(require net/ftp)
Line 1,323 ⟶ 1,619:
(ftp-download-file conn "." "README")
(ftp-close-connection conn))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,329 ⟶ 1,625:
{{works with|rakudo|2018.04}}
 
<syntaxhighlight lang="raku" perl6line>use Net::FTP;
 
my $host = 'speedtest.tele2.net';
Line 1,345 ⟶ 1,641:
say $_<name> for $ftp.ls;
 
$ftp.get( '1KB.zip', :binary );</langsyntaxhighlight>
 
{{out}}
Line 1,368 ⟶ 1,664:
 
=={{header|REBOL}}==
<syntaxhighlight 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
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'net/ftp'
 
Net::FTP.open('ftp.ed.ac.uk', "anonymous","aaa@gmail.com" ) do |ftp|
Line 1,382 ⟶ 1,678:
puts ftp.list
ftp.getbinaryfile("make.notes.tar")
end</langsyntaxhighlight>
The connection is closed automatically at the end of the block.
 
=={{header|Rust}}==
Using crate <code>ftp</code> version 3.0.1
<langsyntaxhighlight Rustlang="rust">use std::{error::Error, fs::File, io::copy};
use ftp::FtpStream;
 
Line 1,401 ⟶ 1,697:
copy(&mut stream, &mut file)?;
Ok(())
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|commons-net}}
<langsyntaxhighlight Scalalang="scala">import java.io.{File, FileOutputStream, InputStream}
 
import org.apache.commons.net.ftp.{FTPClient, FTPFile, FTPReply}
Line 1,482 ⟶ 1,778:
ftpClient.logout
}.isFailure) println(s"Failure.")
}</langsyntaxhighlight>
{{Out}}See it in running in your browser by [https://scastie.scala-lang.org/3Lq8ehzIQTCuAOPXWofNLw Scastie (JVM)].
 
Line 1,489 ⟶ 1,785:
[http://seed7.sourceforge.net/libraries/ftp.htm#openFtp(in_string) open] and handle an
[http://seed7.sourceforge.net/libraries/ftp.htm#ftpFileSys ftpFileSys].
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "ftp.s7i";
 
Line 1,506 ⟶ 1,802:
writeln(getFile(ftp, "README"));
close(ftp);
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">require('Net::FTP');
 
var ftp = %s'Net::FTP'.new('ftp.ed.ac.uk', Passive => 1);
Line 1,518 ⟶ 1,814:
ftp.binary; # set binary mode
ftp.get("make.notes.tar");
ftp.quit;</langsyntaxhighlight>
 
=={{header|Tcl}}==
===Using package ftp===
<syntaxhighlight lang="tcl">
<lang Tcl>
package require ftp
 
Line 1,532 ⟶ 1,828:
::ftp::Type $conn binary
::ftp::Get $conn README README
</syntaxhighlight>
</lang>
 
===Using a virtual file system===
An alternative approach that uses the package [http://sourceforge.net/projects/tclvfs/ TclVFS] to access ftp:// paths as a virtual file system.
 
<langsyntaxhighlight lang="tcl">
package require vfs::urltype
vfs::urltype::Mount ftp
Line 1,550 ⟶ 1,846:
}
file copy README [file join $dir README]
</syntaxhighlight>
</lang>
 
The file <tt>vfsftpfix.tcl</tt> with the passive mode patch (see http://wiki.tcl.tk/12837):
<langsyntaxhighlight lang="tcl">
# Replace vfs::ftp::Mount to enable vfs::ftp to work in passive
# mode and make that the default.
Line 1,604 ⟶ 1,900:
return $fd
}
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
Uses sftp which os available on all Linux distress by default. The commands are identical to ftp. This example uses the public free sftp server at test.rebex.net , the credentials are demo/password :
 
<syntaxhighlight lang="bash">
Aamrun $ sftp demo@test.rebex.net
Password:
Connected to test.rebex.net.
sftp> ls
pub readme.txt
sftp> cd pub
sftp> ls
example
sftp> ls example
example/KeyGenerator.png example/KeyGeneratorSmall.png example/ResumableTransfer.png example/WinFormClient.png example/WinFormClientSmall.png example/imap-console-client.png example/mail-editor.png example/mail-send-winforms.png
example/mime-explorer.png example/pocketftp.png example/pocketftpSmall.png example/pop3-browser.png example/pop3-console-client.png example/readme.txt example/winceclient.png example/winceclientSmall.png
sftp> cd example
sftp> get KeyGenerator.png
Fetching /pub/example/KeyGenerator.png to KeyGenerator.png
/pub/example/KeyGenerator.png 100% 36KB 146.4KB/s 00:00
sftp> exit
Aamrun$
</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
import net.ftp
 
fn main() {
result := ftp_client_test() or {println('Error: something went wrong') exit(1)}
println(result)
}
 
 
fn ftp_client_test() ?[]u8 {
mut zftp := ftp.new()
mut blob := []u8{}
defer {
zftp.close() or {
println('Error: failure to close ftp')
exit(10)
}
}
connect_result := zftp.connect('ftp.redhat.com') or {
println('Error: failed to connect')
exit(1)
}
login_result := zftp.login('ftp', 'ftp') or {
println('Error: failed to login')
exit(2)
}
pwd := zftp.pwd() or {
println('Error: failed to login')
exit(3)
}
if (connect_result == true) && (login_result == true) && (pwd.len > 0) {
zftp.cd('/') or {
println('Error: failed to get root directory')
exit(4)
}
}
dir_list1 := zftp.dir() or {
println('Error: failed to get directory listing')
exit(5)
}
if dir_list1.len > 0 {
zftp.cd('/suse/linux/enterprise/11Server/en/SAT-TOOLS/SRPMS/') or {
println('Error: failed to get directory listing')
exit(6)
}
}
dir_list2 := zftp.dir() or {
println('Error: failed to get directory listing')
exit(7)
}
if dir_list2.len > 0 {
if dir_list2.contains('katello-host-tools-3.3.5-8.sles11_4sat.src.rpm') == true {
blob = zftp.get('katello-host-tools-3.3.5-8.sles11_4sat.src.rpm') or {
println('Error: failed to get directory listing')
exit(8)
}
}
}
if blob.len <= 0 {
println('Error: failed to get data')
exit(9)
}
return blob
}
</syntaxhighlight>
 
=={{header|Wren}}==
Line 1,610 ⟶ 1,996:
{{libheader|ftplib}}
An embedded program so we can ask the C host to communicate with ''ftplib'' for us.
<langsyntaxhighlight ecmascriptlang="wren">/* ftpFTP.wren */
 
var FTPLIB_CONNMODE = 1
Line 1,641 ⟶ 2,027:
ftp.dir("", ".")
ftp.get("ftp.README", "README", FTPLIB_ASCII)
ftp.quit()</langsyntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
Line 1,777 ⟶ 2,163:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "ftpFTP.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 1,793 ⟶ 2,179:
free(script);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,816 ⟶ 2,202:
=={{header|zkl}}==
Using the cURL library, doing this from the REPL. Moving around in the tree isn't supported.
<langsyntaxhighlight 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
Line 1,827 ⟶ 2,213:
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</langsyntaxhighlight>
The resulting file foo.mp3 has a nice six minute description of what can happen when returning from space.
 
9,476

edits