Created
October 10, 2021 20:02
-
-
Save ganchuhang/d2376b53acb0af198f356f47dae16e45 to your computer and use it in GitHub Desktop.
C# SSH tunneled mongodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Console.WriteLine($"SSH Tunnel Start"); | |
PrivateKeyFile[] key1 = new PrivateKeyFile[] { new PrivateKeyFile("C:\\Users\\Administrator\\.ssh\\fifasports2.pem") }; | |
List<AuthenticationMethod> method1 = new List<AuthenticationMethod>(); | |
method1.Add(new PrivateKeyAuthenticationMethod("centos", key1)); | |
using (var ssh = new SshClient(new ConnectionInfo("1.1.1.1", "centos", method1.ToArray()))) | |
{ | |
ssh.Connect(); | |
var command = ssh.CreateCommand("hostnamectl"); | |
var result = command.Execute(); | |
Console.WriteLine(result); | |
var port = new ForwardedPortLocal(IPAddress.Loopback.ToString(), 27017, "mongo2.net", 27017); | |
ssh.AddForwardedPort(port); | |
port.Start(); | |
Console.WriteLine($"Port is start = {port.IsStarted}"); | |
var client = new MongoClient($"mongodb://developer:=x=@127.0.0.1:27017/dbpull?authSource=admin&serverSelectionTimeoutMS=5000"); | |
var database = client.GetDatabase("admin"); | |
try | |
{ | |
database.RunCommandAsync((Command<BsonDocument>)"{ping:1}").Wait(); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.InnerException.Message); | |
return; | |
} | |
Console.WriteLine("MONGO OK"); | |
Console.WriteLine($"SSH Tunnel End"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment