一佳一

记录像1+1一样简洁的代码

导航

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

Posted on 2023-02-08 14:08  一佳一  阅读(232)  评论(0编辑  收藏  举报
     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隧道将数据库地址172.19.1.15映射本地
       var portFoward = new ForwardedPortLocal("localhost", 5432, "172.19.1.15", 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" }
}