Client SFTP del componente sgcIndy per Delphi

· Componenti

Il trasferimento file sicuro rimane uno dei pilastri dell'integrazione enterprise. Che tu stia scambiando dati con partner bancari, sincronizzando file con server remoti o automatizzando pipeline di deployment, SFTP (SSH File Transfer Protocol) è lo standard del settore per spostare file in modo sicuro su reti non fidate.

Il pacchetto sgcIndy include TIdSFTPClient: un componente client SFTP Delphi nativo che funziona su SSH senza richiedere strumenti da riga di comando esterni o eseguibili di terze parti. Supporta upload e download di file, gestione directory, symbolic link, attributi dei file, tracciamento dell'avanzamento e algoritmi crittografici moderni, il tutto tramite un'API pulita ed event-driven.

Questo articolo copre l'intero set di funzionalità e fornisce codice Delphi pronto all'uso per le operazioni SFTP più comuni.

Caratteristiche principali

File Transfer
Upload and download files with configurable buffer sizes and real-time progress events. Transfer from file paths or directly from TStream objects.
Directory Operations
List directories with full metadata, create and remove directories, and resolve paths including symbolic links.
Modern Cryptography
Curve25519, ECDH, AES-GCM, Ed25519 keys, and HMAC-SHA2. Configurable algorithm negotiation for compliance requirements.
Multiple Auth Methods
Password, public key (RSA, ECDSA, Ed25519), and keyboard-interactive authentication. Host key verification with fingerprint callbacks.
File Attributes & Permissions
Read and modify file permissions, ownership, timestamps, and sizes. Full support for Unix-style mode bits and symbolic links.
Progress & Events
Track transfer progress with bytes transferred and total size. Cancelable transfers. Error, connect, and disconnect events.

Quick start — connessione e download di un file

Un esempio minimale che si connette a un server remoto, scarica un file e si disconnette.

var
  oSFTP: TIdSFTPClient;
begin
  oSFTP := TIdSFTPClient.Create(nil);
  Try
    oSFTP.Host := 'sftp.example.com';
    oSFTP.Port := 22;
    oSFTP.Authentication.Username := 'deploy';
    oSFTP.Authentication.Password := 'secret';
    oSFTP.Connect;
    // Download a file
    oSFTP.Get('/data/report.csv', 'C:\local\report.csv');
    oSFTP.Disconnect;
  Finally
    oSFTP.Free;
  End;
end;

Autenticazione

The component supports three authentication methods. All three are enabled by default — the client and server negotiate the most appropriate method automatically.

Password Authentication

oSFTP.Authentication.Username := 'admin';
oSFTP.Authentication.Password := 'secret';

Public Key Authentication

oSFTP.Authentication.Username := 'deploy';
oSFTP.Authentication.PrivateKeyFile := 'C:\keys\id_rsa';
oSFTP.Authentication.PublicKeyFile := 'C:\keys\id_rsa.pub';
oSFTP.Authentication.Passphrase := 'keypassphrase';

Host Key Verification

Verify the server's identity by inspecting the host key fingerprint in the OnSSHHostKey event.

oSFTP.OnSSHHostKey := OnHostKey;
procedure TForm1.OnHostKey(Sender: TObject;
  const aHostKeyType, aFingerprint: string;
  var aAction: TIdSSHHostKeyVerification);
begin
  // Verify fingerprint against known hosts
  if aFingerprint = 'SHA256:xyzABC123...' then
    aAction := sshHostKeyAccept
  else
    aAction := sshHostKeyReject;
end;

File Operations

Upload & Download

// Upload a file
oSFTP.Put('C:\local\data.zip', '/uploads/data.zip');
// Download a file
oSFTP.Get('/reports/monthly.pdf', 'C:\local\monthly.pdf');
// Upload from a stream
oSFTP.Put(oMemoryStream, '/uploads/stream-data.bin');
// Download to a stream
oSFTP.Get('/data/export.csv', oFileStream);

String Convenience Methods

// Read a remote file into a string
vContent := oSFTP.GetFileAsString('/config/settings.json');
// Write a string to a remote file
oSFTP.PutFileFromString('{"key":"value"}', '/config/settings.json');
// Delete a remote file
oSFTP.Delete('/tmp/old-file.log');
// Rename / move a file
oSFTP.Rename('/data/temp.csv', '/data/final.csv');
// Create a symbolic link
oSFTP.Symlink('/data/final.csv', '/data/latest.csv');

Directory Operations

// List directory contents with full metadata
var
  oItems: TIdSFTPDirectoryItems;
  i: Integer;
begin
  oItems := oSFTP.ListDirectory('/data');
  for i := 0 to Length(oItems) - 1 do
    WriteLn(oItems[i].Filename + ' - ' +
      IntToStr(oItems[i].Attrs.Size) + ' bytes');
end;
// Create and remove directories
oSFTP.MakeDirectory('/data/archive/2026');
oSFTP.RemoveDirectory('/data/temp');
// Get current working directory
vPath := oSFTP.GetCurrentDirectory;
// Resolve a path (follows symlinks, resolves . and ..)
vRealPath := oSFTP.RealPath('../data/../data/./file.txt');

File Attributes & Information

// Check existence
if oSFTP.FileExists('/data/report.csv') then
  WriteLn('File found');
if oSFTP.DirectoryExists('/data/archive') then
  WriteLn('Directory exists');
// Get file size
vSize := oSFTP.FileSize('/data/report.csv');
// Get full attributes (size, permissions, timestamps, UID/GID)
var
  oAttrs: TIdSFTPFileAttributes;
begin
  oAttrs := oSFTP.Stat('/data/report.csv');
  WriteLn('Size: ' + IntToStr(oAttrs.Size));
  WriteLn('Permissions: ' + IntToStr(oAttrs.Permissions));
end;

Transfer Progress & Cancellation

The OnSFTPProgress event fires during every file transfer, providing real-time tracking with the ability to cancel mid-transfer.

oSFTP.OnSFTPProgress := OnProgress;
procedure TForm1.OnProgress(Sender: TObject;
  const aFilename: string;
  aTransferred, aTotal: Int64;
  var Cancel: Boolean);
begin
  ProgressBar1.Max := aTotal;
  ProgressBar1.Position := aTransferred;
  Label1.Caption := Format('%s: %d / %d bytes',
    [aFilename, aTransferred, aTotal]);
  // Set Cancel := True to abort the transfer
  Cancel := FUserCancelled;
end;

Cryptographic Algorithm Configuration

The component supports modern cryptographic standards. The defaults are secure, but you can customize algorithm negotiation for compliance or interoperability requirements.

Categoria Supported Algorithms
Key Exchange Curve25519, ECDH (P-256, P-384, P-521), DH Group14/16
Host Keys Ed25519, ECDSA (P-256, P-384, P-521), RSA (SHA2-256, SHA2-512)
Ciphers AES-256/192/128-CTR, AES-256/128-GCM
MACs HMAC-SHA2-256, HMAC-SHA2-512, HMAC-SHA1
// Restrict to only the strongest algorithms
oSFTP.Algorithms.Ciphers := 'aes256-gcm@openssh.com'
		,aes256-ctr';
oSFTP.Algorithms.KexAlgorithms := 'curve25519-sha256';
oSFTP.Algorithms.MACs := 'hmac-sha2-256,hmac-sha2-512';

Complete Example

A production-ready example that connects with public key authentication, lists a directory, downloads a file with progress tracking, and handles errors.

uses
  IdSFTPClient, IdSSHClasses;
var
  oSFTP: TIdSFTPClient;
  oItems: TIdSFTPDirectoryItems;
  i: Integer;
begin
  oSFTP := TIdSFTPClient.Create(nil);
  Try
    // Connection
    oSFTP.Host := 'sftp.example.com';
    oSFTP.Port := 22;
    // Public key authentication
    oSFTP.Authentication.Username := 'deploy';
    oSFTP.Authentication.PrivateKeyFile := 'C:\keys\id_ed25519';
    // Events
    oSFTP.OnSFTPProgress := OnProgress;
    oSFTP.OnSFTPError := OnError;
    oSFTP.OnSSHHostKey := OnHostKey;
    // Connect
    oSFTP.Connect;
    // List remote directory
    oItems := oSFTP.ListDirectory('/data');
    for i := 0 to Length(oItems) - 1 do
      WriteLn(oItems[i].Filename);
    // Download file with progress
    oSFTP.Get('/data/backup.tar.gz', 'C:\backups\backup.tar.gz');
    // Disconnect
    oSFTP.Disconnect;
  Finally
    oSFTP.Free;
  End;
end;

Methods Reference

Metodo Descrizione
GetDownload file to local path or TStream
PutUpload file from local path or TStream
DeleteDelete remote file
RenameRename or move remote file
ListDirectoryList directory contents with metadata
MakeDirectoryCreate remote directory
Stat / LStatGet file attributes (with/without symlink resolution)
FileExists / DirectoryExistsCheck if file or directory exists
Symlink / ReadLinkCreate or read symbolic links
GetFileAsString / PutFileFromStringString-based convenience methods