栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java, jsch , ssh , ppk 密钥文件, 连接远程数据库 mysql

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java, jsch , ssh , ppk 密钥文件, 连接远程数据库 mysql

服务器基于安全考虑未暴露不必要的端口, 

有些时候我们需要远程连接这些端口, 比如只有3306 仅允许本地连接, 这个时候我们可以通过ssh proxy 方式连接. 

直接上代码:

package com.etoak.demo;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;


public class SSHProxy {
    private static final SSHProxy proxy = new SSHProxy();
    private Session session;

    
    public static SSHProxy getInstance() {
        return proxy;
    }

    
    public void createSSHSession(String host, int port, String userId, String keyFilePath) throws JSchException {
        JSch jsch = new JSch();
        this.session = jsch.getSession(userId, host, port);
        jsch.addIdentity(keyFilePath);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
    }

    
    public void forward(int localePort, String targetHost, int targetPort) throws JSchException {
        session.setPortForwardingL(localePort, targetHost, targetPort);
    }

    
    public static void main(String[] args) {
        // ===============1. 实例化===============
        SSHProxy proxy = SSHProxy.getInstance();
        // ===============2. 创建SSH会话===============
        //SSH服务器
        String host = "x.x.x.x";
        //ssh连接私钥路径, 放在项目中,使用配置文件代替
        String keyFilePath = "/Users/lizhenhe/Downloads/jsh-ssh-demo/src/main/resources/key.ppk";
        //SSH服务端口
        int port = 22;
        //SSH连接用户名
        String userId = "root";
        try {
            proxy.createSSHSession(host, port, userId, keyFilePath);
        } catch (JSchException e) {
            e.printStackTrace();
        }

        // ===============3. 端口跳转 ===============
        // 程序中使用  jdbc:mysql://localhost:13306 连接, 其中13306 是通过ssh 代理过来的

        // 本地服务端口, 这个可以根据需求更改
        int localePort = 13306;


        // 目标服务器
        String targetHost = "localhost";
        // 目标服务端口
        int targetPort = 3306;
        try {
            proxy.forward(localePort, targetHost, targetPort);
            //fixme 上线时 修改成logger
            System.out.println("通过ssh转发端口成功");
        } catch (JSchException e) {
            e.printStackTrace();
        }

    }

}
    
    
      com.jcraft
      jsch
      0.1.55
    

这个时候 你就可以直接通过代码或常用客户端 连接转发出来的端口 如上例中 13306 来连接数据库了, 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020598.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号