안전한 파일 전송은 엔터프라이즈 통합의 핵심이에요. 은행 파트너와 데이터를 교환하거나, 원격 서버와 파일을 동기화하거나, 배포 파이프라인을 자동화할 때 SFTP(SSH 파일 전송 프로토콜)는 신뢰할 수 없는 네트워크에서 파일을 안전하게 이동하는 업계 표준이에요.
The sgcIndy package includes TIdSFTPClient — a native Delphi SFTP client component that runs over SSH without requiring external command-line tools or third-party executables. It supports file upload and download, directory management, symbolic links, file attributes, progress tracking, and modern cryptographic algorithms — all through a clean, event-driven API.
이 글에서는 전체 기능 세트를 다루고 가장 일반적인 SFTP 작업을 위한 바로 사용 가능한 Delphi 코드를 제공해요.
주요 기능
|
파일 전송 설정 가능한 버퍼 크기와 실시간 진행률 이벤트로 파일을 업로드하고 다운로드해요. 파일 경로 또는 TStream 객체에서 직접 전송할 수 있어요. |
디렉토리 작업 전체 메타데이터로 디렉토리를 나열하고, 디렉토리를 생성 및 제거하며, 심볼릭 링크를 포함한 경로를 확인해요. |
최신 암호화 Curve25519, ECDH, AES-GCM, Ed25519 키, HMAC-SHA2를 지원해요. 규정 준수 요구 사항에 맞게 알고리즘 협상을 설정할 수 있어요. |
|
다양한 인증 방법 비밀번호, 공개 키(RSA, ECDSA, Ed25519), 키보드 대화형 인증을 지원해요. 지문 콜백으로 호스트 키를 확인해요. |
파일 속성 및 권한 파일 권한, 소유권, 타임스탬프, 크기를 읽고 수정해요. Unix 스타일 모드 비트와 심볼릭 링크를 완전히 지원해요. |
진행률 및 이벤트 전송된 바이트와 총 크기로 전송 진행률을 추적해요. 전송 취소가 가능해요. 오류, 연결, 연결 해제 이벤트를 지원해요. |
Quick Start — Connect and Download a File
원격 서버에 연결하고 파일을 다운로드한 후 연결을 해제하는 최소한의 예제예요.
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;
인증
The component supports three authentication methods. All three are enabled by default — the client and server negotiate the most appropriate method automatically.
비밀번호 인증
oSFTP.Authentication.Username := 'admin';
oSFTP.Authentication.Password := 'secret';
공개 키 인증
oSFTP.Authentication.Username := 'deploy';
oSFTP.Authentication.PrivateKeyFile := 'C:\keys\id_rsa';
oSFTP.Authentication.PublicKeyFile := 'C:\keys\id_rsa.pub';
oSFTP.Authentication.Passphrase := 'keypassphrase';
호스트 키 확인
OnSSHHostKey 이벤트에서 호스트 키 지문을 검사해 서버 신원을 확인하세요.
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;
파일 작업
업로드 및 다운로드
// 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);
문자열 편의 메서드
// 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');
디렉토리 작업
// 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');
파일 속성 및 정보
// 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;
전송 진행률 및 취소
OnSFTPProgress 이벤트는 모든 파일 전송 중에 발생하며 전송 중간에 취소할 수 있는 실시간 추적을 제공해요.
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;
암호화 알고리즘 설정
컴포넌트는 최신 암호화 표준을 지원해요. 기본값은 안전하지만 규정 준수 또는 상호 운용성 요구 사항에 맞게 알고리즘 협상을 커스텀할 수 있어요.
| 카테고리 | 지원 알고리즘 |
|---|---|
| 키 교환 | Curve25519, ECDH (P-256, P-384, P-521), DH Group14/16 |
| 호스트 키 | Ed25519, ECDSA (P-256, P-384, P-521), RSA (SHA2-256, SHA2-512) |
| 암호 | AES-256/192/128-CTR, AES-256/128-GCM |
| MAC | 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';
전체 예제
공개 키 인증으로 연결하고, 디렉토리를 나열하며, 진행률 추적으로 파일을 다운로드하고, 오류를 처리하는 프로덕션 준비 예제예요.
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;
메서드 참조
| 메서드 | Description |
|---|---|
Get | 파일을 로컬 경로 또는 TStream으로 다운로드해요 |
Put | 로컬 경로 또는 TStream에서 파일을 업로드해요 |
Delete | 원격 파일을 삭제해요 |
Rename | 원격 파일의 이름을 바꾸거나 이동해요 |
ListDirectory | 메타데이터와 함께 디렉토리 내용을 나열해요 |
MakeDirectory | 원격 디렉토리를 생성해요 |
Stat / LStat | 파일 속성을 가져와요 (심볼릭 링크 해석 포함/미포함) |
FileExists / DirectoryExists | 파일 또는 디렉토리 존재 여부를 확인해요 |
Symlink / ReadLink | 심볼릭 링크를 생성하거나 읽어요 |
GetFileAsString / PutFileFromString | 문자열 기반 편의 메서드예요 |
