7.6.212-stable Switch to dev

ssh > sftp

Source

The sftp module provides SFTP (SSH File Transfer Protocol) functionality for securely transferring files between local and remote servers.

Types

Sftp

The main type for establishing and managing SFTP connections.

Constructor Parameters

Parameter Type Required Description
addr String Yes Server address (e.g., "example.com", "localhost:22")
auth SshAuth Yes Either SshPasswordAuth or SshKeyAuth

Methods

Method Parameters Return Type Description
get remote: String, local: String void Downloads a file from remote to local
put local: String, remote: String void Uploads a file from local to remote
list dirpath: String Array<SftpFile> Lists files/directories at a remote path
delete filepath: String void Deletes a file on the remote server

SftpFile

Represents a file or directory entry returned by the list method.

Field Type Description
path String Full path of the file/directory
stat FileStat File statistics (size, times, etc.)
type FileType Type of entry (file, directory)

Examples

Creating an SFTP Connection

Password authentication

var sftp = Sftp {
    addr: "sftp.example.com:22",
    auth: SshPasswordAuth {
        username: "myuser",
        password: "mypassword",
    },
};

Public key authentication

var sftp = Sftp {
    addr: "sftp.example.com",
    auth: SshKeyAuth {
        username: "username",
        pubkey: "/home/user/.ssh/id_ed25519.pub",
        privkey: "/home/user/.ssh/id_ed25519",
        passphrase: "key_passphrase",
    },
};

Downloading a File

// Download a remote file to local filesystem
sftp.get("/remote/path/report.csv", "/local/path/report.csv");

Uploading a File

// Upload a local file to remote server
// Note: Remote directories are created automatically if they don't exist
sftp.put("/local/path/data.json", "/remote/uploads/data.json");

Listing Directory Contents

// List all files in a remote directory
var files = sftp.list("/remote/uploads/");

for (_, file in files) {
    println(file.path);
    println(file.type);
}

Deleting a Remote File

// Delete a file on the remote server
sftp.delete("/remote/path/old_file.txt");

Complete Workflow Example

fn main() {
    // Establish connection
    var sftp = Sftp {
        addr: "sftp.myserver.com",
        auth: SshPasswordAuth {
            username: "admin",
            password: "123secret",
        },
    };

    // Upload new data
    sftp.put("/local/exports/daily_report.csv", "/uploads/daily_report.csv");

    // List uploaded files
    var uploads = sftp.list("/uploads/");
    println("Files in /uploads/:");
    for (_, f in uploads) {
        println("  - ${f.path}");
    }

    // Download a processed result
    sftp.get("/results/analysis.json", "/local/downloads/analysis.json");

    // Clean up old files
    sftp.delete("/uploads/old_report.csv");
}