Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Run a command on an SSH server

This example asks an SSH server to run the fixed command status and copies its standard output to a Delphi stream. The server must allow the signed-in account to run that command through an SSH exec request.

The components on this page are normally placed on a form or a data module at design time and set up in the Object Inspector. The sample creates them in code instead, because code shows at a glance which properties are changed from their default values.

Connect to the verified server

uses
  System.Classes, System.SysUtils, stAES, stSHA256,
  StreamSec.DSI.Arith, StreamSec.DSI.ECArith, StreamSec.DSI.ArithComp,
  StreamSec.SSH.SocketClient, StreamSec.SSH.Transport,
  StreamSec.SSH.ClientChannel, StreamSec.SSH.Types;
type
  TStatusClient = class(TstSSHSocketClient)
  private
    fCommandTransport: iSSHTransport;
    procedure RequestStatus(const aChannel: iSSHClientChannel);
  protected
    procedure InitTransport(const aTransport: iSSHTransport); override;
  public
    destructor Destroy; override;
    procedure ReadStatus(aOutput: TStream; aTimeoutMs: Cardinal);
  end;
function ConnectStatusClient(const aHost: string; aPort: Word;
  aPin: TstECDSAPublicKey; const aUser, aPassword: string): TStatusClient;
begin
  if aPin = nil then
    raise EArgumentException.Create('An ECDSA P-256 host key is required');
  Result := TStatusClient.Create(nil);
  try
    Result.Host := aHost;
    Result.Port := aPort;
    Result.ServerECDSAKey := aPin;
    Result.ServerKeyOptions.SelectedOptionNames := 'ecdsa-sha2-nistp256';
    Result.KexOptions.SelectedOptionNames := 'ecdh-sha2-nistp256';
    Result.CipherC2SOptions.SelectedOptionNames := 'aes128-ctr';
    Result.CipherS2COptions.SelectedOptionNames := 'aes128-ctr';
    Result.MacC2SOptions.SelectedOptionNames := 'hmac-sha2-256';
    Result.MacS2COptions.SelectedOptionNames := 'hmac-sha2-256';
    Result.UserAuthOptions.SelectedOptionNames := 'password';
    Result.Password := aPassword;
    Result.ConnectToHost;
    if not Result.Login(aUser) then
      raise Exception.Create('SSH sign-in refused');
  except
    Result.Free;
    raise;
  end;
end;

Pass an enabled ECDSA P-256 public key that you obtained from the administrator. Keep it alive while using the client. See Configure and verify an SSH server's host key for loading the key. The host selects the network destination. The pinned key identifies the server during key exchange, before password sign-in.

Request one command

procedure TStatusClient.InitTransport(const aTransport: iSSHTransport);
begin
  inherited;
  fCommandTransport := aTransport;
end;

destructor TStatusClient.Destroy;
begin
  fCommandTransport := nil;
  inherited;
end;

procedure TStatusClient.RequestStatus(const aChannel: iSSHClientChannel);
const
  cCommand = 'status';
var
  lMessage: TBytes;
  lOffset: Integer;
begin
  SetLength(lMessage, 1 + 4 + 4 + Length('exec') + 1 + 4 + Length(cCommand));
  lOffset := 0;
  EncodeByte(SSH_MSG_CHANNEL_REQUEST, lMessage, lOffset);
  EncodeUInt32(aChannel.RemoteChannel, lMessage, lOffset);
  EncodeStr('exec', lMessage, lOffset);
  EncodeBoolean(True, lMessage, lOffset);
  EncodeStr(cCommand, lMessage, lOffset);
  fCommandTransport.Lock;
  try
    fCommandTransport.Send(lMessage, 0, lOffset);
  finally
    fCommandTransport.Unlock;
  end;
end;

The client channel exposes a method for starting a named subsystem. For exec, the sample retains the SSH transport through the component's protected InitTransport hook and writes the request with the library's packet encoders. The request names the peer's channel and asks the server to confirm that it accepted the command. Use a command agreed with the administrator. The sample sends the ASCII word status exactly as written.

Read standard output

procedure TStatusClient.ReadStatus(aOutput: TStream; aTimeoutMs: Cardinal);
var
  lChannel: iSSHClientChannel;
  lBuffer: TBytes;
  lCount: Integer;
  lStart: UInt64;
  lEnded: Boolean;

  procedure CheckTime;
  begin
    if TThread.GetTickCount64 - lStart >= aTimeoutMs then
      raise eSSHClientChannelError.Create('SSH command timed out');
  end;

begin
  lStart := TThread.GetTickCount64;
  lChannel := CreateChannel(DefaultWindowSize, DefaultPacketSize);
  try
    while lChannel.State = csConnecting do begin
      CheckTime;
      TThread.Sleep(1);
    end;
    if lChannel.State <> csConnected then
      raise eSSHClientChannelError.Create('SSH session channel did not open');
    RequestStatus(lChannel);
    while (lChannel.RequestState = rsNone) and (lChannel.State = csConnected) do begin
      CheckTime;
      TThread.Sleep(1);
    end;
    if lChannel.RequestState <> rsSuccess then
      raise eSSHClientChannelError.Create('SSH command request was not accepted');
    lChannel.SendEOF;
    SetLength(lBuffer, 8192);
    repeat
      CheckTime;
      lEnded := lChannel.PeerEOF;
      lCount := lChannel.Recv(lBuffer, 0, Length(lBuffer), False);
      if lCount > 0 then
        aOutput.WriteBuffer(lBuffer[0], lCount)
      else if not lEnded then
        TThread.Sleep(1);
    until lEnded and (lCount = 0);
  finally
    lChannel.Close;
  end;
end;

Call ReadStatus with a writable stream and a timeout in milliseconds, for example 10000. It opens a fresh session channel, closes the command's standard input with SendEOF, and drains standard output into your stream. The bytes are written at the stream's current position. Decode them using the encoding agreed with the server. Free the client after the last call.

A refused request or a timeout raises eSSHClientChannelError. A failure during reading can leave partial output in the stream. The client channel discards standard error and the remote exit status. A return from ReadStatus means the request was accepted and the output channel ended. If the command needs to report an application result, have it include that result in standard output.

The SSH notes describe the client transport and channels.

Reference

TstSSHSocketClient · TstECDSAPublicKey · StreamSec.SSH.SocketClient · StreamSec.SSH.ClientChannel · StreamSec.SSH.Transport · StreamSec.SSH.Types · StreamSec.DSI.ArithComp

Related tasks