Table of Contents

Class SshCommand

Namespace
Renci.SshNet
Assembly
Renci.SshNet.dll

Represents SSH command that can be executed.

public class SshCommand : IDisposable
Inheritance
SshCommand
Implements
Inherited Members

Properties

CommandText

Gets the command text.

public string CommandText { get; }

Property Value

string

CommandTimeout

Gets or sets the command timeout.

public TimeSpan CommandTimeout { get; set; }

Property Value

TimeSpan

The command timeout.

Error

Gets the standard error of the command by reading ExtendedOutputStream, when extended data has been sent which has been marked as stderr.

public string Error { get; }

Property Value

string

ExitSignal

Gets the name of the signal due to which the command terminated violently, if applicable, otherwise null.

public string? ExitSignal { get; }

Property Value

string

Remarks

The value (if it exists) is supplied by the server and is usually one of the following, as described in https://datatracker.ietf.org/doc/html/rfc4254#section-6.10: ABRT, ALRM, FPE, HUP, ILL, INT, KILL, PIPE, QUIT, SEGV, TER, USR1, USR2.

ExitStatus

Gets the number representing the exit status of the command, if applicable, otherwise null.

public int? ExitStatus { get; }

Property Value

int?

Remarks

The value is not null when an exit status code has been returned from the server. If the command terminated due to a signal, ExitSignal may be not null instead.

See Also

ExtendedOutputStream

Gets the extended output stream.

public Stream ExtendedOutputStream { get; }

Property Value

Stream

OutputStream

Gets the output stream.

public Stream OutputStream { get; }

Property Value

Stream

Result

Gets the standard output of the command by reading OutputStream.

public string Result { get; }

Property Value

string

Methods

BeginExecute()

Begins an asynchronous command execution.

public IAsyncResult BeginExecute()

Returns

IAsyncResult

An IAsyncResult that represents the asynchronous command execution, which could still be pending.

Exceptions

InvalidOperationException

Asynchronous operation is already in progress.

SshException

Invalid operation.

ArgumentException

CommandText property is empty.

SshConnectionException

Client is not connected.

SshOperationTimeoutException

Operation has timed out.

BeginExecute(AsyncCallback?)

Begins an asynchronous command execution.

public IAsyncResult BeginExecute(AsyncCallback? callback)

Parameters

callback AsyncCallback

An optional asynchronous callback, to be called when the command execution is complete.

Returns

IAsyncResult

An IAsyncResult that represents the asynchronous command execution, which could still be pending.

Exceptions

InvalidOperationException

Asynchronous operation is already in progress.

SshException

Invalid operation.

ArgumentException

CommandText property is empty.

SshConnectionException

Client is not connected.

SshOperationTimeoutException

Operation has timed out.

BeginExecute(AsyncCallback?, object?)

Begins an asynchronous command execution.

public IAsyncResult BeginExecute(AsyncCallback? callback, object? state)

Parameters

callback AsyncCallback

An optional asynchronous callback, to be called when the command execution is complete.

state object

A user-provided object that distinguishes this particular asynchronous read request from other requests.

Returns

IAsyncResult

An IAsyncResult that represents the asynchronous command execution, which could still be pending.

Exceptions

InvalidOperationException

Asynchronous operation is already in progress.

SshException

Invalid operation.

ArgumentException

CommandText property is empty.

SshConnectionException

Client is not connected.

SshOperationTimeoutException

Operation has timed out.

BeginExecute(string, AsyncCallback?, object?)

Begins an asynchronous command execution.

public IAsyncResult BeginExecute(string commandText, AsyncCallback? callback, object? state)

Parameters

commandText string

The command text.

callback AsyncCallback

An optional asynchronous callback, to be called when the command execution is complete.

state object

A user-provided object that distinguishes this particular asynchronous read request from other requests.

Returns

IAsyncResult

An IAsyncResult that represents the asynchronous command execution, which could still be pending.

Exceptions

SshConnectionException

Client is not connected.

SshOperationTimeoutException

Operation has timed out.

CancelAsync(bool, int)

Cancels a running command by sending a signal to the remote process.

public void CancelAsync(bool forceKill = false, int millisecondsTimeout = 500)

Parameters

forceKill bool

if true send SIGKILL instead of SIGTERM.

millisecondsTimeout int

Time to wait for the server to reply.

Remarks

This method stops the command running on the server by sending a SIGTERM (or SIGKILL, depending on forceKill) signal to the remote process. When the server implements signals, it will send a response which populates ExitSignal with the signal with which the command terminated.

When the server does not implement signals, it may send no response. As a fallback, this method waits up to millisecondsTimeout for a response and then completes the SshCommand object anyway if there was none.

If the command has already finished (with or without cancellation), this method does nothing.

Exceptions

InvalidOperationException

Command has not been started.

CreateInputStream()

Creates and returns the input stream for the command.

public Stream CreateInputStream()

Returns

Stream

The stream that can be used to transfer data to the command's input stream.

Examples

This example shows how to stream some data to 'cat' and have the server echo it back.

using (SshCommand command = mySshClient.CreateCommand("cat"))
{
    Task executeTask = command.ExecuteAsync(CancellationToken.None);

    using (Stream inputStream = command.CreateInputStream())
    {
        inputStream.Write("Hello World!"u8);
    }

    await executeTask;

    Console.WriteLine(command.ExitStatus); // 0
    Console.WriteLine(command.Result); // "Hello World!"
}

Remarks

Callers should ensure that Dispose() is called on the returned instance in order to notify the command that no more data will be sent. Failure to do so may result in the command executing indefinitely.

Dispose()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

public void Dispose()

Dispose(bool)

Releases unmanaged and - optionally - managed resources.

protected virtual void Dispose(bool disposing)

Parameters

disposing bool

true to release both managed and unmanaged resources; false to release only unmanaged resources.

EndExecute(IAsyncResult)

Waits for the pending asynchronous command execution to complete.

public string EndExecute(IAsyncResult asyncResult)

Parameters

asyncResult IAsyncResult

The reference to the pending asynchronous request to finish.

Returns

string

Result.

Exceptions

ArgumentException

Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.

ArgumentNullException

asyncResult is null.

Execute()

Executes command specified by CommandText property.

public string Execute()

Returns

string

Result.

Exceptions

SshConnectionException

Client is not connected.

SshOperationTimeoutException

Operation has timed out.

Execute(string)

Executes the specified command text.

public string Execute(string commandText)

Parameters

commandText string

The command text.

Returns

string

The result of the command execution.

Exceptions

SshConnectionException

Client is not connected.

SshOperationTimeoutException

Operation has timed out.

ExecuteAsync(CancellationToken)

Executes the command asynchronously.

public Task ExecuteAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

The CancellationToken. When triggered, attempts to terminate the remote command by sending a signal.

Returns

Task

A Task representing the lifetime of the command.

Exceptions

InvalidOperationException

Command is already executing. Thrown synchronously.

ObjectDisposedException

Instance has been disposed. Thrown synchronously.

OperationCanceledException

The Task has been cancelled.

SshOperationTimeoutException

The command timed out according to CommandTimeout.