我正在使用此SSH.NET客户端https://github.com/sshnet/SSH.NET/和MongoDB C#最新客户端。根据{{3}},我尝试将SSHStream注入MongoDB客户端设置。我的SSH连接成功。但是我无法通过SSH与MongoDB建立连接。
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;
}
}
感谢您的帮助。
答案 0 :(得分:2)
您可以使用以下代码启动SSH客户端。
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();
现在SSH客户端会将localhost端口5477转发到远程MongoDB数据库服务器。
MongoClient可用于与MongoDB Server通信,主机为localhost,端口为5477。
请参考下面的代码片段以连接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();
以上代码将使用SSH隧道连接到MongoDB Server。