gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:32:50 25 4
gpt4 key购买 nike

我正在使用这个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com