0 votes
by (8.4k points)

I'd like to execute a command on SFTP server. Is it possible?

Applies to: Rebex SFTP

1 Answer

0 votes
by (18.0k points)
Best answer

You can achieve it by utilizing the fact that SFTP runs over SSH. This makes it possible to use SSH's "remote execute" feature to run arbitrary commands at the server (if it was configured to allow that, of course).

Here is a sample class for a "remote execute" on SFTP server:


public class SftpCommandRunner
    public static string RunCommand(Sftp sftp, string command)
        SshChannel channel = null;
            // start an exec session
            channel = sftp.Session.OpenSession();

            // receive all response
            StringBuilder response = new StringBuilder();
            byte[] buffer = new byte[4096];
            while (channel.State == SshChannelState.Connected)
                if (!channel.Poll(sftp.Timeout * 1000, SocketSelectMode.SelectRead))

                int n = channel.Receive(buffer, 0, buffer.Length);
                response.Append(Encoding.Default.GetString(buffer, 0, n));

            return response.ToString().TrimEnd();
            if (channel != null)


Public Class SftpCommandRunner
    Public Shared Function RunCommand(ByVal sftp As Sftp, ByVal command As String) As String
        Dim channel As SshChannel = Nothing
            ''# start an exec session
            channel = sftp.Session.OpenSession()

            ''# receive all response
            Dim response As New StringBuilder()
            Dim buffer As Byte() = New Byte(4095) {}
            While channel.State = SshChannelState.Connected
                If Not channel.Poll(sftp.Timeout * 1000, SocketSelectMode.SelectRead) Then
                    Exit While
                End If

                Dim n As Integer = channel.Receive(buffer, 0, buffer.Length)
                response.Append(Encoding.[Default].GetString(buffer, 0, n))
            End While

            Return response.ToString().TrimEnd()
            If channel IsNot Nothing Then
            End If
        End Try
    End Function
End Class

To execute a command on SFTP server, establish an SFTP connection and call SftpCommandRunner.RunCommand, supplying your Sftp objecet and a command to it.

For instance, for copying a file on remote server, the command for Unix-like OS would be "cp source_path destination_path". For Windows OS, use "copy" instead of "cp".