Skip to content

Transfers and manages files on a remote server over SFTP (SSH file transfer). Sftp.newSession returns an SftpSession. Things to know: the connection is opened lazily by the first operation, and reopened if it was dropped. Host keys: by default any server key is accepted (a warning is logged once per host); pass the server's SHA256 fingerprint as the optional last argument of newSession to pin it, or run the agent with agent.ssh.strictHostKeys=true to require a pinned fingerprint or a known_hosts entry. For key based login call setPrivateKey on the session; the key is a file in the project. Local paths are relative to the project; remote paths are interpreted by the server (relative paths start in the login directory). Failures are raised as errors that contain the remote path and the JSch message. Use secret() for passwords and close sessions with session.close() or Sftp.close().

Functions

Sftp.newSession(username: string, password: string, host: string)→SftpSessionSftp.newSession(username: string, password: string, host: string, port: number)→SftpSessionSftp.newSession(username: string, password: string, host: string, port: number, fingerprint?: string)→SftpSession

Creates an SFTP session for a server. Nothing is sent yet: connecting and logging in happen at the first operation. For key authentication pass an empty password ("") and call setPrivateKey on the session (a key is tried before the password). The optional fingerprint pins the server's SHA256 host key fingerprint (as printed by `ssh-keygen -l`, with or without the "SHA256:" prefix); a server with another key is rejected.

Parameters

username string
User name on the server
password string
Password; use secret(), or "" when logging in with a key
host string
Host name or IP address, without sftp://
port number optional
SSH port; 22 when left out
fingerprint string optional
SHA256 fingerprint of the server's host key, to pin it

Returns

SftpSession A session on an SFTP server: upload, download, list, create and delete files and directories.

Example 1

Password login and upload

local sftp = Sftp.newSession("deploy", secret("sftp_password"), "files.example.com")
sftp.uploadFileTo("output/report.csv", "/incoming/report.csv")
sftp.close()

Example 2

Key login on a custom port

local sftp = Sftp.newSession("deploy", "", "files.example.com", 2222)
sftp.setPrivateKey("keys/deploy_ed25519")
for _, name in ipairs(sftp.listFiles("outgoing")) do
print(name)
end
sftp.close()
Sftp.close()→self

Closes every SFTP session opened with Sftp.newSession in this script.

Returns

self chainable The library itself, so calls can be chained.