Skip to content

Please allow us to customize OutputStream and ExtendedOutputStream before executing an SSH command. #1608

Open
@ScionOfDesign

Description

@ScionOfDesign

I have a use case where I want real time output from the console command to be printed to the console. Unfortunately, the streams that are written to cannot be customized with the existing public interface, even though the PipeStream class is extensible. The best solution I found to do what I need to do unfortunately requires reflection.

A public interface (such as a callback) for this feature would be greatly appreciated.

public static class SshClientExtensions
{
    public static async Task<SshCommand> ConnectAndExecuteCommandAsync(this SshClient client, string command, CancellationToken cancellationToken = default)
    {
        SshCommand sshCommand;
        try
        {
            await client.ConnectAsync(cancellationToken);
            sshCommand = client.CreateCommand(command);
            using CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
            PropertyInfo stdOutProp = typeof(SshCommand).GetProperty(nameof(SshCommand.OutputStream), bindingFlags)!;
            PropertyInfo stdErrProp = typeof(SshCommand).GetProperty(nameof(SshCommand.ExtendedOutputStream), bindingFlags)!;

            PipeStream stdOutStream = (PipeStream)stdOutProp.GetValue(sshCommand)!;
            PipeStream stdErrStream = (PipeStream)stdErrProp.GetValue(sshCommand)!;

            await stdOutStream.DisposeAsync();
            await stdErrStream.DisposeAsync();

            TextWriterPipeStream stdOut = new(Console.Out);
            TextWriterPipeStream stdErr = new(Console.Error);

            stdOutProp.SetValue(sshCommand, stdOut);
            stdErrProp.SetValue(sshCommand, stdErr);

            await sshCommand.ExecuteAsync(cancellationToken);
        }
        catch (Exception e)
        {
            return await Task.FromException<SshCommand>(e);
        }
        finally
        {
            client.Disconnect();
        }
        return sshCommand;
    }

    private sealed class TextWriterPipeStream : PipeStream
    {
        private readonly TextWriter textWriter;

        public TextWriterPipeStream(TextWriter textWriter) : base()
        {
            this.textWriter = textWriter;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            base.Write(buffer, offset, count);
            string output = Encoding.UTF8.GetString(buffer, offset, count);
            textWriter.Write(output);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions