SFTP Client with User and Public Key Authorization

 
This example connects to an SFTP host via the Secure Shell protocol (SSH), authorizes with the user/password or the Public Key algorithms, lists, downloads, and uploads files.
 
 
procedure TForm1.DoOpenDir(const ADir: string);
var
  dir: string;
begin
  dir := ADir;
  if (Length(dir) > 1) and (dir[1] = '/') and (dir[2] = '/') then
  begin
    system.Delete(dir, 1, 1);
  end;
  clSFtp1.ChangeCurrentDir('/');
  clSFtp1.ChangeCurrentDir(dir);
  FillDirList();
end;

procedure TForm1.FillDirList;
begin
  lbList.Items.BeginUpdate();
  try
    lbList.Items.Clear();
    clSFtp1.DirectoryListing();
  finally
    lbList.Items.EndUpdate();
  end;
  lbList.Sorted := False;
  lbList.Sorted := True;
end;
 
procedure TForm1.btnLoginClick(Sender: TObject);
begin
  clSFtp1.Server := edtHost.Text;
  clSFtp1.Port := StrToInt(edtPort.Text);

  clSFtp1.UserName := edtUser.Text;

  clSFtp1.Password := '';
  clSFtp1.UserKey.Clear();

  if (cbAuthorization.ItemIndex = 0) then //user/password authorization
  begin
    clSFtp1.Password := edtPassword.Text;
  end else //public key
  begin
    clSFtp1.UserKey.PrivateKeyFile := edtPrivateKeyFile.Text;
    clSFtp1.UserKey.PassPhrase := edtPassphrase.Text;
  end;

  clSFtp1.Open();

  if (edtStartDir.Text = '') then
  begin
    edtStartDir.Text := clSFtp1.CurrentDir;
  end;
  if (edtStartDir.Text <> '') and (edtStartDir.Text[1] = '/') then
  begin
    DoOpenDir(edtStartDir.Text);
  end;
  UpdateStatuses();
end;
 
procedure TForm1.btnDownloadClick(Sender: TObject);
var
  size: Integer;
  stream: TStream;
begin
  if (lbList.ItemIndex > -1) and
    (lbList.Items[lbList.ItemIndex] <> '') and
    (lbList.Items[lbList.ItemIndex][1] = '/') then
    begin
      SaveDialog1.FileName := lbList.Items[lbList.ItemIndex];
      if SaveDialog1.Execute() then
      begin
        size := clSFtp1.GetFileSize(lbList.Items[lbList.ItemIndex]);
        stream := nil;
        try
          stream := TFileStream.Create(SaveDialog1.FileName, fmCreate);

          clSFtp1.GetFile(lbList.Items[lbList.ItemIndex], stream);
          ShowMessage('Done');
        finally
          stream.Free();
        end;
      end;
    end;
end;

procedure TForm1.btnUploadClick(Sender: TObject);
var
 stream: TStream;
 fileName: string;
begin
  if OpenDialog1.Execute() then
  begin
    stream := TFileStream.Create(OpenDialog1.FileName, fmOpenRead);
    try
      fileName := ExtractFileName(OpenDialog1.FileName);

      clSFtp1.PutFile(stream, fileName);
      ShowMessage('Done');
    finally
      stream.Free();
    end;
  end;
end;

Add Feedback