Sftp
libraryTransfers 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().
- Kind Library, a global in every script
- Category Remote & Infrastructure
- Functions 2
Objects
Functions
-
newSessionSftpSession Creates an SFTP session for a server. -
closeself Closes every SFTP session opened with Sftp.newSession in this script.
newSession()
Section titled “newSession()”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
-
usernamestring - User name on the server
-
passwordstring - Password; use secret(), or "" when logging in with a key
-
hoststring - Host name or IP address, without sftp://
-
portnumber optional - SSH port; 22 when left out
-
fingerprintstring optional - SHA256 fingerprint of the server's host key, to pin it
Returns
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)endsftp.close()close()
Section titled “close()”Sftp.close()→self Closes every SFTP session opened with Sftp.newSession in this script.
Returns