首页 > 数据库 >.NET Core SshClient + Npgsql 实现ssh隧道访问内网数据库

.NET Core SshClient + Npgsql 实现ssh隧道访问内网数据库

时间:2023-02-08 14:26:10浏览次数:43  
标签:USER Core SshClient const string Npgsql SSH new ssh

     private const string SSH_USER = "root";          // ssh账号
        private const string SSH_PASSWORD = ".";         // ssh密码,若使用密钥且没密码时填空
        private const string SSH_PRVKEY = "prd_jump.pem";   // ssh密钥,若使用密码登录时为空
        private const string SSH_HOST = "172.19.0.8"; // ssh服务器
        private const int SSH_PORT = 65432;              // ssh端口

        static void Main(string[] args)
        {
            // 存在密钥文件使用密钥登录,不存在密钥文件使用密码登录
            ConnectionInfo conn = null;
            if (string.IsNullOrEmpty(SSH_PRVKEY))
            {
                conn = new ConnectionInfo(SSH_HOST, SSH_PORT, SSH_USER, new PasswordAuthenticationMethod(SSH_USER, SSH_PASSWORD));
            }
            else
            {
                var pem = new PrivateKeyFile(SSH_PRVKEY);
                conn = new ConnectionInfo(SSH_HOST, SSH_PORT, SSH_USER, new PrivateKeyAuthenticationMethod(SSH_USER, pem));
            }

            // 连接SSH
            var cli = new SshClient(conn);
            cli.Connect();

            //使用SSH隧道将数据库映射本地
            var portFoward = new ForwardedPortLocal("localhost", 5432, "prd-yeeshop-db-pg-master", 5432);
            cli.AddForwardedPort(portFoward);
            portFoward.Start();

            IConfigurationRoot configuration = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", true, true)
             .Build();

            string defaultConnectionString = configuration.GetConnectionString("PrdConnectionString");
            //string defaultConnectionString = configuration.GetConnectionString("TestConnectionString");

            var pgconn = new NpgsqlConnection(defaultConnectionString);
            DataTable datatable = new DataTable();
            using (pgconn)
            {
                pgconn.Open();
                using (var cmd = new NpgsqlCommand("SELECT * FROM accounts LIMIT 10", pgconn))
                {
                    using (NpgsqlDataReader reader = cmd.ExecuteReader())
                    {
                        datatable = ConvertDataReaderToDataTable(reader);
                        PrintCityInfo(datatable);
                    }
                }
            }

            portFoward.Stop();
            // Disconnect from the SSH server
            cli.Disconnect();
        }
{
  "ConnectionStrings": {
    "PrdConnectionString": "Server=localhost;Port=5432;User Id=xxxx;Password=xxxx;Database=testdb" }
}

 

标签:USER,Core,SshClient,const,string,Npgsql,SSH,new,ssh
From: https://www.cnblogs.com/linyijia/p/17101576.html

相关文章