I'm using this SSH.NET client https://github.com/sshnet/SSH.NET/ and MongoDB C# latest client. As per https://jira.mongodb.org/browse/CSHARP-1142 i'm trying to inject SSHStream into MongoDB Client settings. My SSH connection is successful. But i'm not able to establish a connection to MongoDB through SSH.

   static void Main(string[] args)
        MongoClientSettings settings = new MongoClientSettings
            ClusterConfigurator = cb =>
        MongoClient mongoClient = new MongoClient(settings);
        IMongoDatabase db = mongoClient.GetDatabase("testdb");
        var collections = db.ListCollections();

    public static IStreamFactory CustomStreamFac(IStreamFactory istreamfac)

        Stream stream = istreamfac.CreateStream();
        return istreamfac;

public static class Extension
    public static Stream CreateStream(this IStreamFactory isf)
        ConnectionInfo conn = new ConnectionInfo(hostname, port, username, new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile(keyfile, password)));
        SshClient cli = new SshClient(conn);
        ShellStream shellStream = null;
        shellStream = cli.CreateShellStream("Command", 0, 0, 0, 0, 1024);            
        return shellStream;

Any help is appreciated.

  • 1) Can you connect to hostname:port using any SSH client running on the same machine as your C# code? 2) Do you have any reason to believe the CreateShellStream should be able to cooperate with MongoDB? I didn't find any evidence for that in the Jira link. – Martin Prikryl Jun 12 at 11:18
  • @MartinPrikryl Yes, i'm able to connect to the SSH server using this host:port. And no they haven't mentioned anything about CreateShellStream. I'm not sure it'll coperate but I only see this option to convert the sshclient as stream to be passed on to IStreamFactory – Edwin Vivek N Jun 12 at 11:23
  • So start by creating a simple console application that only ssh to that hostname:port. If it does not connect, show us also a log file from your SSH client for comparison. -- Your immediate problem has nothing to do with MongoDB. -- Also you didn't confirm that you run your SSH client on the same machine as your C# code. - How do you run your C# btw? – Martin Prikryl Jun 12 at 11:27
  • @MartinPrikryl I do not have a problem with SSH connection. My SSH is hosted in Amazon EC2 and cli.Connect(); creates a successful connection. What is the SSH client you are referring to? My C# console(SSH.NET) is the client I use. To confirm the SSH communication I used RoboMongo as an additional SSH client on the same machine where my C# code is and established a communication. – Edwin Vivek N Jun 12 at 12:31
  • So where do you get "connection refused exception"? Not in SSH code? Do you get it in MongoDB code? – Martin Prikryl Jun 12 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.