Remote server administration, automated deployments, configuration management, e infrastructure monitoring — tutti di questi rely su secure shell access. Whether hai bisogno di a execute a single command su un remoto host, apre an interactive terminal session, o impostare up a port-forwarding tunnel, SSH è il protocol che rende it possible.
The sgcIndy package includes TIdSSHClient — a native Delphi SSH client componente che implementa il SSH-2 protocol con completo supporto per command execution, interactive shells, pseudo-terminal allocation, porta forwarding, keep-alive, e modern cryptographic algorithms. No external SSH executables, no DLL wrappers — pure Delphi componente architecture con an event-driven API.
This articolo walks attraverso il chiave funzionalità e fornisce Delphi codice esempi per il la maggior parte common SSH utilizzare cases.
Key Features
|
Command Execution Execute remoto commands e capture stdout, stderr, e exit codes. One-line convenience metodo o completo channel-based control. |
Interactive Shell Open interactive shell sessions con pseudo-terminal support. Invia commands, ricevere output asynchronously, e gestire terminal resize. |
Port Forwarding Set up direct TCP/IP tunnels e reverse forwarding. Access remoto servizi attraverso encrypted SSH tunnels. |
|
Modern Cryptography Curve25519, ECDH, AES-GCM, Ed25519 keys. Configurable algorithm negotiation con secure defaults out di il box. |
Multiple Auth Methods Password, public chiave (RSA, ECDSA, Ed25519), e keyboard-interactive authentication. Host chiave verification tramite evento callback. |
Multi-Channel Up a 10 concurrent canali per connection. Run multiple commands, shells, o tunnels simultaneously over a single SSH session. |
Quick Start — Execute a Remoto Command
The simplest utilizzare case: connect, esegui a command, ottenere il output, e disconnettere — tutti in un pochi lines.
var
oSSH: TIdSSHClient;
vOutput: string;
begin
oSSH := TIdSSHClient.Create(nil);
Try
oSSH.Host := 'server.example.com';
oSSH.Port := 22;
oSSH.Authentication.Username := 'admin';
oSSH.Authentication.Password := 'secret';
oSSH.Connect;
// Execute a command e capture il output
vOutput := oSSH.Execute('df -h');
WriteLn(vOutput);
oSSH.Disconnect;
Finally
oSSH.Free;
End;
end;
One-liner. Il Execute metodo apre a channel, esegue il command, waits per il result, e restituisce il output come a string — perfect per scripted automation.
Authentication
Three autenticazione metodi sono supportati. Tutti three sono abilitato per impostazione predefinita e il client negotiates automaticamente con il server.
Password
oSSH.Authentication.Username := 'admin';
oSSH.Authentication.Password := 'secret';
Public Key
oSSH.Authentication.Username := 'deploy';
oSSH.Authentication.PrivateKeyFile := 'C:\keys\id_ed25519';
oSSH.Authentication.PublicKeyFile := 'C:\keys\id_ed25519.pub';
oSSH.Authentication.Passphrase := 'keypassphrase';
Keyboard-Interactive
Handle multi-step autenticazione prompts (MFA, OTP, sicurezza questions) attraverso il OnSSHKeyboardInteractive event.
oSSH.OnSSHKeyboardInteractive := OnKeyboardInteractive;
procedure TForm1.OnKeyboardInteractive(Sender: TObject;
const aName, aInstruction: string;
aPrompts: TStrings; aEchos: TList; aResponses: TStrings);
begin
// Respond to each prompt (e.g., "Password:", "OTP:")
se aPrompts.Count > 0 then
aResponses.Add('mypassword');
end;
Host Key Verification
oSSH.OnSSHHostKey := OnHostKey;
procedure TForm1.OnHostKey(Sender: TObject;
const aHostKeyType, aFingerprint: string;
var aAction: TIdSSHHostKeyVerification);
begin
// Accept o reject based on known fingerprint
aAction := sshHostKeyAccept;
end;
Command Execution
Two approaches per in esecuzione remoto commands: il convenience Execute metodo per simple cases, o il channel-based API per completo control over input, output, e exit status.
Simple: Execute Method
// Execute e ottenere output (30-second timeout da default)
vOutput := oSSH.Execute('ls -la /var/log');
// Custom timeout (10 seconds)
vOutput := oSSH.Execute('cat /etc/hostname', 10000);
Advanced: Channel-Based Execution
For asynchronous execution con separate stdout/stderr gestione e exit status tracking.
// Open a canale e execute a command
var
vChannelId: Cardinal;
begin
vChannelId := oSSH.OpenChannel;
oSSH.RequestExec(vChannelId, 'tar czf /tmp/backup.tar.gz /data');
// Output arrives tramite OnSSHChannelData event
// Exit status arrives tramite OnSSHChannelExitStatus event
end;
// Gestire stdout
procedure TForm1.OnChannelData(Sender: TObject;
aChannelId: Cardinal; const aData: TIdBytes);
begin
Memo1.Lines.Add(BytesToString(aData));
end;
// Gestire stderr
procedure TForm1.OnChannelExtendedData(Sender: TObject;
aChannelId: Cardinal; aDataType: Cardinal; const aData: TIdBytes);
begin
MemoErrors.Lines.Add(BytesToString(aData));
end;
// Gestire exit status
procedure TForm1.OnExitStatus(Sender: TObject;
aChannelId: Cardinal; aExitStatus: Integer);
begin
WriteLn('Command exited con code: ' + IntToStr(aExitStatus));
end;
Interactive Shell Sessions
Open a pseudo-terminal e interact con a remoto shell — ideal per creando SSH terminal emulators o automating interactive CLI workflows.
// Open channel, richiesta PTY, poi richiesta shell
var
vChannelId: Cardinal;
begin
vChannelId := oSSH.OpenChannel;
// Request a pseudo-terminal (xterm, 80x24)
oSSH.RequestPTY(vChannelId, 'xterm', 80, 24);
// Start il shell
oSSH.RequestShell(vChannelId);
// Invia commands to il shell
oSSH.SendChannelData(vChannelId, 'cd /var/log' + #13#10);
oSSH.SendChannelData(vChannelId, 'tail -f syslog' + #13#10);
end;
Terminal Resize & Signals
// Notify il server di terminal resize
oSSH.SendWindowChange(vChannelId, 120, 40, 0, 0);
// Invia Ctrl+C (interrupt signal)
oSSH.SendSignal(vChannelId, 'INT');
// Set an environment variable prima in esecuzione commands
oSSH.SetEnvironmentVariable(vChannelId, 'LANG', 'en_US.UTF-8');
// Signal end di input
oSSH.SendEOF(vChannelId);
Port Forwarding (SSH Tunnels)
Create encrypted tunnels a access remoto servizi come se loro erano local. Useful per securely accessing databases, admin panels, o internal APIs behind firewalls.
Direct TCP/IP Tunneling (Local Forward)
// Tunnel a un remote database attraverso SSH
var
vTunnelId: Cardinal;
begin
vTunnelId := oSSH.OpenDirectTCPIP(
'db-internal.example.com', // Remote host
5432, // Remote porta (PostgreSQL)
'127.0.0.1', // Originator IP
0); // Originator port
// Send/receive dati attraverso il tunnel
oSSH.SendChannelData(vTunnelId, vDatabaseQuery);
end;
Reverse Forwarding (Remote Forward)
// Ask il server to forward a remote porta to us
oSSH.RequestForwarding('0.0.0.0', 8080);
// Cancel il forwarding
oSSH.CancelForwarding('0.0.0.0', 8080);
Keep-Alive & Connessione Options
Prevent idle connessioni da being dropped da firewalls o load balancers con il built-in keep-alive mechanism.
// Invia keep-alive every 30 seconds, disconnettere dopo 3 failures
oSSH.KeepAlive.Enabled := True;
oSSH.KeepAlive.Interval := 30;
oSSH.KeepAlive.MaxCount := 3;
// Connection options
oSSH.SSHOptions.ConnectTimeout := 10000; // 10 seconds
oSSH.SSHOptions.ReadTimeout := 30000; // 30 seconds
oSSH.SSHOptions.MaxChannels := 10; // Concurrent channels
Cryptographic Algorithm Configuration
The defaults sono secure e modern. Customize algorithm negotiation quando compliance policies o legacy server compatibility demand it.
| Category | 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 |
// Customize algorithm preferences
oSSH.Algorithms.KexAlgorithms := 'curve25519-sha256';
oSSH.Algorithms.Ciphers := 'aes256-gcm@openssh.com'
,aes256-ctr';
oSSH.Algorithms.HostKeyAlgorithms := 'ssh-ed25519,rsa-sha2-256';
oSSH.Algorithms.MACs := 'hmac-sha2-256';
// Force re-keying to refresh encryption
oSSH.Rekey;
Events Reference
The componente fornisce granular evento callbacks per ogni stage di il SSH lifecycle.
| Evento | Fired When |
|---|---|
OnSSHConnect | SSH connessione established |
OnSSHDisconnect | SSH connessione chiude (with reason e code) |
OnSSHError | SSH errore occurs |
OnSSHAuthSuccess / OnSSHAuthFailure | Authentication succeeds o fails |
OnSSHHostKey | Host chiave ha bisogno verification (accept/reject) |
OnSSHChannelData | Data (stdout) ricevuto su un channel |
OnSSHChannelExtendedData | Extended dati (stderr) ricevuto su un channel |
OnSSHChannelExitStatus | Remote command exit codice received |
OnSSHChannelExitSignal | Remote process terminated da signal (with signal name) |
OnSSHKeyboardInteractive | Server richieste keyboard-interactive responses |
OnSSHAuthBanner | Server invia an autenticazione banner message |
Complete Example: Automated Deployment Script
A completamente configured SSH client che connette con chiave authentication, esegue deployment commands, e captures exit status.
uses
IdSSHClient, IdSSHClasses;
var
oSSH: TIdSSHClient;
vOutput: string;
begin
oSSH := TIdSSHClient.Create(nil);
Try
// Connection
oSSH.Host := 'production.example.com';
oSSH.Port := 22;
// Key-based authentication
oSSH.Authentication.Username := 'deploy';
oSSH.Authentication.PrivateKeyFile := 'C:\keys\deploy_ed25519';
// Keep connessione alive attraverso firewalls
oSSH.KeepAlive.Enabled := True;
oSSH.KeepAlive.Interval := 30;
// Events
oSSH.OnSSHHostKey := OnHostKey;
oSSH.OnSSHError := OnError;
// Connect
oSSH.Connect;
// Run deployment commands
vOutput := oSSH.Execute('cd /opt/app && git pull origin main');
WriteLn(vOutput);
vOutput := oSSH.Execute('systemctl restart myapp');
WriteLn(vOutput);
vOutput := oSSH.Execute('systemctl status myapp');
WriteLn(vOutput);
// Disconnect
oSSH.Disconnect;
Finally
oSSH.Free;
End;
end;
