How to write my SFTP / SSH server in .NET C#

+1 vote
asked Jun 9, 2015 by Rebex KB (8,130 points)
edited Jun 23, 2015 by Rebex KB

I am in need of building my own simple SFTP / SSH server for .NET in C# or VisualBasic but I do not want to dive too deep into technical details. The only additional requirement I need is the ability to implement custom commands.

Do you have a ready-to-use component or API for this problem?

If it supports Mono, Xamarin.iOS,Android or even Compact Framework this is a big plus as well.

Applies to: File Server

1 Answer

+1 vote
answered Jun 9, 2015 by Tomas Knopp (58,580 points)
selected Jun 9, 2015 by Rebex KB
 
Best answer

With the Rebex File Server component, writing your own SFTP/SSH server is as easy as a few lines of C# code:

var server = new FileServer();

// bind SFTP (runs over SSH) to port 9022
server.Bind(9022, FileServerProtocol.Sftp);

// load a server private key from encrypted 'serverkey.ppk' file
server.Keys.Add(new SshPrivateKey("server-key.ppk", "password"));

// add a user (specify username, password and virtual root path)
server.Users.Add("user01", "password", @"c:\data\user01");

// start the server in the background
server.Start();

Writing custom SSH commands is possible via the FileServer.ShellCommand event, see this code sample:

// implement some simple custom shell commands
server.ShellCommand += (sender, e) =>
{
    switch (e.Command)
    {
        case "date":
            e.WriteLine(DateTime.UtcNow);
            break;
        case "say":
            e.WriteLine(string.Join(" ", e.Arguments));
            break;
        case "fail":
            e.WriteLine("Command failed.");
            e.ExitCode = 1;
            break;
    }
};

(See more custom commands examples.)

Rebex File Server supports .NET, Mono, .NET Compact Framework, as well as Xamarin.iOS and Xamarin.Android frameworks.

If you want to give it a try, just download the free 30-day trial.

See other code examples for typical scenarios like limiting file system access, SFTP sever user management, private keys, user authentication, server management, etc..

...