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

标签 c# mongodb ssh ssh.net

我正在使用这个 SSH.NET 客户端 https://github.com/sshnet/SSH.NET/和 MongoDB C# 最新客户端。根据 https://jira.mongodb.org/browse/CSHARP-1142我正在尝试将 SSSHtream 注入(inject) 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;
    }
}

感谢任何帮助。

最佳答案

您可以使用以下代码启动 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 客户端会将本地主机端口 5477 转发到远程 MongoDB 数据库服务器。

MongoClient 可用于与 MongoDB Server 通信,主机为 localhost,端口为 5477。

引用以下代码片段连接 MongoDB 服务器。

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 服务器。

关于c# - 如何在 MongoDB C# 中连接 SSH.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560795/

相关文章:

c# - 如何通过NEST客户流利的语法为Elasticsearch索引定义多个分析器

php - "The login is invalid "cPanel 问题

git - maven-release-plugin 不使用作业配置或/和 .ssh/config 中提供的 ssh key

Git:git@gitlab.com:当我按下 "synchronize changes"按钮时权限被拒绝(公钥)

mongodb - 更新 MongoDB 中的集合时出错

c# - WebApi 2 中 IHostBufferPolicySelector 上下文中的空 RouteData

c# - 查询字符串唯一字符串生成器?

c# - 具有 CLR 函数的 System.Security.SecurityException

mongodb - 用户评分模式 - 键/值数据库

mongodb - 在存储在 mongo 中的文件中搜索文本