ftp
An FTP and FTPS client: listing a directory, uploading and downloading files.
import ftp
This package connects to FTP servers, for uploading a site to shared hosting or pulling files off old equipment and suppliers' servers. Plain FTP sends the password and the data unencrypted; wherever the server supports it, use DialTLS, which encrypts both the commands and the data with AUTH TLS. When the server also speaks SSH, SFTP through ssh is the better choice: one encrypted connection, no separate data channel.
Transfers go in passive mode (EPSV, or PASV when the server lacks it), which works from behind a firewall; active mode (PORT) is not offered. The parsing functions, such as ParseListLine, are available for writing tools of your own too.
Things to know:
- Call
Binarybefore transfers, or a server in ASCII mode may change line endings inside images and archives. UploadandDownloadhold the whole file in memory, and an interrupted transfer starts again from the beginning; there is no resume. Fine for site files and reports, not for multi-gigabyte backups.Read,WriteandAppendcarry astr, so they are for text: binary content stops at the first zero byte. UseUploadandDownloadfor anything else.- Servers that require TLS session reuse on the data connection refuse every transfer; see the last section.
Publish a site to shared hosting
The usual job: connect with DialTLS, refuse to go on unless both the commands and the data are encrypted, log in, and upload a build directory with UploadDir. Switch to binary mode with Binary before any transfer, or some servers will change the line endings inside images and archives. Keeping the old index.html under another name with Rename gives you something to go back to.
import ftp
func main:
mut c := ftp.DialTLS("ftp.example-host.com", 21)
if not ftp.Ok(c):
println "cannot connect:", ftp.LastReply(c)
ret 1
end
if not ftp.Secure(c) or not ftp.SecureData(c):
println "the server would not encrypt the session, stopping"
ftp.Close(c)
ret 1
end
if not ftp.Login(c, "site-user", "app-password"):
println "login failed:", ftp.LastCode(c), ftp.LastReply(c)
ftp.Close(c)
ret 1
end
_ := ftp.Binary(c)
_ := ftp.MkdirAll(c, "/public_html")
if ftp.Exists(c, "/public_html/index.html"):
_ := ftp.Rename(c, "/public_html/index.html", "/public_html/index.old.html")
end
if not ftp.UploadDir(c, "dist", "/public_html"):
println "upload failed:", ftp.LastReply(c)
ret 1
end
println "uploaded, index.html is", ftp.Size(c, "/public_html/index.html"), "bytes"
ftp.Quit(c)
ftp.Close(c)
ret 0
endThis needs a real server, so it is only checked here. Every function that talks to the server leaves the reply in LastCode and LastReply, so after a false you can always print what the server said.
Fetch only the new files
List returns one FileInfo per entry with the name, the size and whether it is a directory or a link. Comparing that with what is already on disk turns a full download into a cheap sync, which suits a nightly job that collects reports from a supplier.
import ftp
import os
func main:
mut c := ftp.DialTLS("files.example.com", 21)
if not ftp.Ok(c) or not ftp.Login(c, "reports", "app-password"):
println "cannot log in:", ftp.LastReply(c)
ret 1
end
_ := ftp.Binary(c)
_ := os.MkdirAll("reports")
mut fetched := 0
mut skipped := 0
each f in ftp.List(c, "/daily"):
if f.is_dir or f.is_link:
continue
end
local := "reports/" + f.name
if os.Exists(local):
skipped++
continue
end
if ftp.Download(c, "/daily/" + f.name, local):
fetched++
else:
println "failed:", f.name, ftp.LastReply(c)
end
end
println "fetched", fetched, "new files, skipped", skipped
ftp.Quit(c)
ftp.Close(c)
ret 0
endFor a stricter check than "the file exists", compare f.size with the local size, or ModTime with the time you stored after the last run.
Read a directory listing yourself
FTP has no fixed format for listings; most servers send the same columns as ls -l. ParseListLine reads such a line into a FileInfo, which is useful when you get listings from somewhere else, such as a log or a ListRaw call, and want to work with them without a connection.
import ftp
import str
func main:
raw := "drwxr-xr-x 2 ftp ftp 4096 Jan 01 2026 old\n-rw-r--r-- 1 ftp ftp 120034 Oct 02 08:10 sales-2026-10-01.csv\n-rw-r--r-- 1 ftp ftp 118702 Oct 03 08:10 sales-2026-10-02.csv\n-rw-r--r-- 1 ftp ftp 2251800 Oct 03 08:12 photos.zip\nlrwxrwxrwx 1 ftp ftp 20 Oct 03 08:12 latest.csv -> sales-2026-10-02.csv"
mut total := 0 as i64
mut files := 0
mut biggest := ftp.FileInfo {}
each line in str.Split(raw, "\n"):
f := ftp.ParseListLine(line)
if f.is_dir:
println "dir ", f.name
continue
end
if f.is_link:
println "link", f.name
continue
end
println "file", f.name, f.size, f.raw_date
files++
total += f.size
if f.size > biggest.size:
biggest = f
end
end
println files, "files,", total, "bytes; biggest:", biggest.name
endServers that require TLS session reuse
Some FTPS servers insist that the data connection resumes the TLS session of the command connection. vsftpd does this with its default require_ssl_reuse=YES, and so do FileZilla Server and the Rebex test server. This package does not resume sessions yet, so on those servers logging in works but every listing and transfer is refused with reply 425:
import ftp
func main:
mut c := ftp.DialTLS("test.rebex.net", 21)
if not ftp.Ok(c) or not ftp.Login(c, "demo", "password"):
println "cannot log in:", ftp.LastCode(c), ftp.LastReply(c)
ret 1
end
println "encrypted:", ftp.Secure(c), ftp.SecureData(c)
println "system:", ftp.System(c)
entries := ftp.List(c, "/")
if entries.Len() == 0 and ftp.LastCode(c) >= 400:
println "listing refused:", ftp.LastReply(c)
end
each f in entries:
println f.name, f.is_dir
end
ftp.Quit(c)
ftp.Close(c)
ret 0
endRun against test.rebex.net, it printed:
encrypted: true true
system: 215 UNIX Type: L8
listing refused: 425 Cannot secure data connection - TLS session resumption required.
If you run the server, set require_ssl_reuse=NO in vsftpd. If you do not, and the server offers SFTP, use ssh instead; fall back to plain Dial only on a network you trust, since it sends the password in the clear.
Which function for which job
| Job | Use |
|---|---|
| Connect securely | DialTLS, or DialTLSWith for a private CA; Dial then AuthTLS does the same in two steps |
| Check that encryption is on | Secure for the commands, SecureData for the files |
| Small text files | Read, Write, Append |
| Files on disk | Upload, Download, UploadDir, DownloadDir |
| Look before you act | Exists, IsDir, Size, ModTime, List |
| A command with no function of its own | Command, which returns the reply code |
Types
FileInfo
struct FileInfo| Name | Type | Description |
|---|---|---|
name | str = "" | The name. |
size | i64 = 0 | The size. |
is_dir | bool = false | It is a directory. |
is_link | bool = false | It is a link. |
mode | str = "" | The permissions, such as rw-r--r--. |
raw_date | str = "" | The date exactly as the server wrote it. |
import ftp
func main:
println ftp.ReplyCode("230 Login successful."), ftp.ReplyCode("broken")
println ftp.IsFinalLine("211-Features:"), ftp.IsFinalLine("211 End")
println ftp.ParsePasv("227 Entering Passive Mode (192,168,1,10,19,137)")
println ftp.ParseEpsv("229 Entering Extended Passive Mode (|||50000|)")
file := ftp.ParseListLine("-rw-r--r-- 1 ftp ftp 1024 Sep 30 12:00 notes.txt")
println file.name, file.size, file.is_dir, file.is_link, file.mode, file.raw_date
folder := ftp.ParseListLine("drwxr-xr-x 2 ftp ftp 4096 Jan 01 2026 backup")
println folder.name, folder.is_dir
link := ftp.ParseListLine("lrwxrwxrwx 1 ftp ftp 7 Mar 03 09:15 current -> backup")
println link.name, link.is_link
endClient
struct Client| Name | Type | Description |
|---|---|---|
conn | tcp.Conn | The TCP connection of the commands. |
ok | bool = false | The connection is healthy. |
host | str = "" | The host. |
port | int = 21 | The port. |
rxbuf | str = "" | The data that was read. |
last_reply | str = "" | The last reply of the server. |
last_code | int = 0 | The code of the last reply. |
secure | bool = false | The command channel is encrypted. |
tls_idx | int = -1 | The index of the TLS connection. |
prot_p | bool = false | The data channel is encrypted too. |
tls_cfg | tls.Config | The TLS configuration. |
import ftp
import tls
func main:
mut c := ftp.DialTLS("ftp.example.com", 21)
if not ftp.Ok(c) or not ftp.Login(c, "ali", "s3cret"):
println ftp.LastCode(c), ftp.LastReply(c)
ret
end
println ftp.Secure(c), ftp.SecureData(c)
println ftp.System(c)
println ftp.Features(c)
_ := ftp.Binary(c)
println ftp.Pwd(c)
_ := ftp.MkdirAll(c, "/site/assets")
_ := ftp.Cwd(c, "/site")
_ := ftp.Write(c, "index.html", "<h1>hello</h1>")
_ := ftp.Append(c, "log.txt", "one more line\n")
println ftp.Read(c, "index.html")
println ftp.Upload(c, "logo.png", "assets/logo.png")
println ftp.Download(c, "log.txt", "log-copy.txt")
each entry in ftp.List(c, "."):
println entry.name, entry.size, entry.is_dir
end
each name in ftp.NameList(c, "assets"):
println name
end
println ftp.ListRaw(c, ".").Len() > 0
println ftp.Size(c, "index.html"), ftp.ModTime(c, "index.html")
println ftp.IsDir(c, "assets"), ftp.IsLink(c, "current"), ftp.Exists(c, "old.html")
_ := ftp.Rename(c, "log.txt", "log-1.txt")
_ := ftp.Move(c, "log-1.txt", "archive/log-1.txt")
_ := ftp.Delete(c, "archive/log-1.txt")
_ := ftp.CdUp(c)
_ := ftp.Mkdir(c, "tmp")
_ := ftp.Rmdir(c, "tmp")
_ := ftp.RemoveAll(c, "/site/old")
_ := ftp.UploadDir(c, "public", "/site")
_ := ftp.DownloadDir(c, "/site", "backup")
println ftp.Command(c, "SITE CHMOD 644 index.html")
println ftp.Noop(c)
_ := ftp.Ascii(c)
ftp.Quit(c)
ftp.Close(c)
mut plain := ftp.Dial("ftp.example.com", 21)
println ftp.AuthTLS(plain)
mut cfg := tls.NewConfig("ftp.example.com")
cfg.ca_file = "company-ca.pem"
mut configured := ftp.DialTLSWith("ftp.example.com", 21, cfg)
mut upgraded := ftp.Dial("ftp.example.com", 21)
println ftp.AuthTLSWith(upgraded, cfg)
ftp.Close(plain)
ftp.Close(configured)
ftp.Close(upgraded)
endFunctions
Dial
func Dial(host: str, port: int): ClientThe example for this item is shown with the ones above: ftp-Client.salam
AuthTLSWith
func AuthTLSWith(c &: Client, cfg: tls.Config): boolThe example for this item is shown with the ones above: ftp-Client.salam
AuthTLS
func AuthTLS(c &: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
DialTLS
func DialTLS(host: str, port: int): ClientThe example for this item is shown with the ones above: ftp-Client.salam
DialTLSWith
func DialTLSWith(host: str, port: int, cfg: tls.Config): ClientThe example for this item is shown with the ones above: ftp-Client.salam
Secure
func Secure(c: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
SecureData
func SecureData(c: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
Login
func Login(c &: Client, user: str, password: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Quit
func Quit(c &: Client)The example for this item is shown with the ones above: ftp-Client.salam
Close
func Close(c &: Client)The example for this item is shown with the ones above: ftp-Client.salam
Ok
func Ok(c: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
LastReply
func LastReply(c: Client): strThe example for this item is shown with the ones above: ftp-Client.salam
LastCode
func LastCode(c: Client): intThe example for this item is shown with the ones above: ftp-Client.salam
Command
func Command(c &: Client, line: str): intThe example for this item is shown with the ones above: ftp-Client.salam
Noop
func Noop(c &: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
System
func System(c &: Client): strThe example for this item is shown with the ones above: ftp-Client.salam
Features
func Features(c &: Client): strThe example for this item is shown with the ones above: ftp-Client.salam
Binary
func Binary(c &: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
Ascii
func Ascii(c &: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
Pwd
func Pwd(c &: Client): strThe example for this item is shown with the ones above: ftp-Client.salam
Cwd
func Cwd(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
CdUp
func CdUp(c &: Client): boolThe example for this item is shown with the ones above: ftp-Client.salam
Mkdir
func Mkdir(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Rmdir
func Rmdir(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
MkdirAll
func MkdirAll(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
ListRaw
func ListRaw(c &: Client, path: str): strThe example for this item is shown with the ones above: ftp-Client.salam
List
func List(c &: Client, path: str): Vector<FileInfo>The example for this item is shown with the ones above: ftp-Parse.salam
NameList
func NameList(c &: Client, path: str): Vector<str>The example for this item is shown with the ones above: ftp-Client.salam
Size
func Size(c &: Client, path: str): i64The example for this item is shown with the ones above: ftp-Client.salam
ModTime
func ModTime(c &: Client, path: str): strYYYYMMDDHHMMSS form.The example for this item is shown with the ones above: ftp-Client.salam
IsDir
func IsDir(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
IsLink
func IsLink(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Exists
func Exists(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Read
func Read(c &: Client, remote: str): strDownload for it.The example for this item is shown with the ones above: ftp-Client.salam
Write
func Write(c &: Client, remote: str, data: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Append
func Append(c &: Client, remote: str, data: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Download
func Download(c &: Client, remote: str, local: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Upload
func Upload(c &: Client, local: str, remote: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Delete
func Delete(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Rename
func Rename(c &: Client, from_path: str, to_path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
Move
func Move(c &: Client, from_path: str, to_path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
RemoveAll
func RemoveAll(c &: Client, path: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
DownloadDir
func DownloadDir(c &: Client, remote: str, local: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
UploadDir
func UploadDir(c &: Client, local: str, remote: str): boolThe example for this item is shown with the ones above: ftp-Client.salam
ReplyCode
func ReplyCode(line: str): intThe example for this item is shown with the ones above: ftp-Parse.salam
IsFinalLine
func IsFinalLine(line: str): boolThe example for this item is shown with the ones above: ftp-Parse.salam
ParsePasv
func ParsePasv(reply: str): strThe example for this item is shown with the ones above: ftp-Parse.salam
ParseEpsv
func ParseEpsv(reply: str): intThe example for this item is shown with the ones above: ftp-Parse.salam
ParseListLine
func ParseListLine(line: str): FileInfoThe example for this item is shown with the ones above: ftp-Parse.salam