Reputation: 564
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 =>
{
cb.RegisterStreamFactory(CustomStreamFac);
}
};
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);
cli.Connect();
ShellStream shellStream = null;
shellStream = cli.CreateShellStream("Command", 0, 0, 0, 0, 1024);
return shellStream;
}
}
Any help is appreciated.
Upvotes: 1
Views: 2624
Reputation: 259
You can start the SSH client using below code.
ConnectionInfo conn = new ConnectionInfo(SSHServerHost, SSHServerPort,SSHServerUserName, new PrivateKeyAuthenticationMethod(SSHServerUserName, new PrivateKeyFile(PrivateKeyPath,SSHServerPassword)));
SshClient = new SshClient(conn);
SshClient.Connect();
ForwardedPortLocal forwardedPortLocal = new ForwardedPortLocal("127.0.0.1",5477,MongoDBHost, MongoDBPort);
SshClient.AddForwardedPort(forwardedPortLocal);
forwardedPortLocal.Start();
Now SSH client will forward localhost port 5477 to remote MongoDB database server.
MongoClient can be used to communicate with MongoDB Server with host as localhost and port as 5477.
Refer below code snippet to connect with MongoDB Server.
MongoConnection connection = new MongoConnection();
MongoDBClientConnection clientConnection = new MongoDBClientConnection(){MongoDBClient = new MongoClient( MongoClientSettings settings = new MongoClientSettings
{
Server = new MongoServerAddress(localhost, 5477)
};)}
connection.MongoDBServer = clientConnection.MongoDBClient.GetServer();
connection.MongoDBServer.Connect();
Above code will connect with MongoDB Server using SSH tunnel.
Upvotes: 4