首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在MongoDB C#中连接SSH.NET

如何在MongoDB C#中连接SSH.NET
EN

Stack Overflow用户
提问于 2019-06-12 19:11:18
回答 1查看 1.4K关注 0票数 1

我正在使用这个SSH.NET client https://github.com/sshnet/SSH.NET/和MongoDB C#最新客户端。根据https://jira.mongodb.org/browse/CSHARP-1142,我尝试将SSHStream注入到MongoDB客户端设置中。我的SSH连接成功。但是我不能通过SSH建立到MongoDB的连接。

代码语言:javascript
复制
   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;
    }
}

任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

发布于 2019-07-15 17:20:50

您可以使用以下代码启动SSH客户端。

代码语言:javascript
复制
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客户端将把本地主机端口5477转发到远程MongoDB数据库服务器。

MongoClient可用于与本地主机为主机、端口为5477的MongoDB服务器进行通信。

请参阅下面的代码片段以连接到MongoDB服务器。

代码语言:javascript
复制
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();

上面的代码将使用MongoDB隧道与Server连接。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56560795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档