我正在使用这个SSH.NET client https://github.com/sshnet/SSH.NET/和MongoDB C#最新客户端。根据https://jira.mongodb.org/browse/CSHARP-1142,我尝试将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;
}
}任何帮助都是非常感谢的。
发布于 2019-07-15 17:20:50
您可以使用以下代码启动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可用于与本地主机为主机、端口为5477的MongoDB服务器进行通信。
请参阅下面的代码片段以连接到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();上面的代码将使用MongoDB隧道与Server连接。
https://stackoverflow.com/questions/56560795
复制相似问题