无法通过ssh使用java连接到mysql数据库

xa9qqrwz  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(319)

我知道关于这个问题已经有很多问题了,相信我,我已经看完了所有的问题。
一些背景知识,我正在使用intellij,我可以用intellij的数据源工具连接到数据库,也可以用终端ssh连接到服务器本身。出于某种原因,即使我尝试用java做同样的事情,它也不起作用。这是我的密码:

String serverIP = "123.45.67.890"
String username = "root";
String password = "password";

// Establish SSH tunnel with server if not running locally
try {
    if (!Inet4Address.getLocalHost().getHostAddress().equals(ServerIP) {
        System.out.println("Remote connection detected.");
        System.out.println("Establishing SSH Tunnel...");
        JSch jSch = new JSch();
        Session session = jSch.getSession(username, ServerIP, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        System.out.printf("Connecting to remote server at %s...\n", ServerIP);
        session.connect();
        System.out.println("Connected!");
        session.setPortForwardingL(3306, ServerIP, 3306);
    }
} catch (Exception e) {
    e.printStackTrace();
}

// Load mySQL Driver
System.out.println("Loading driver...");
try {
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
    throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}

String url = String.format("jdbc:mysql://%s:3306/db_name", ServerIP);

// Connect to database
System.out.println("Connecting to database...");

try (Connection connection = DriverManager.getConnection(url, username, password)) {
    System.out.println("Database connected!");
    this.connection = connection;
} catch (SQLException e) {
    this.connection = null;
    throw new IllegalStateException("Cannot connect to database!", e);
}

我得到的错误是:

Remote connection detected.
Establishing SSH Tunnel...
Connecting to remote server at 123.45.67.890...
Connected!
Loading driver...
Driver loaded!
Connecting to database...

java.lang.IllegalStateException: Cannot connect to database!

    ...
    a bunch of crap
    ...
Caused by: java.sql.SQLException: null,  message from server: "Host 'my.personal.computer.local.hostname' is not allowed to connect to this MySQL server"
    ...
    a bunch more crap
    ...

在我看来,由于某种原因,java代码没有使用ssh隧道,我花了很多精力复制stackoverflow代码,而是粗暴地尝试正常连接。我做错什么了?
更多信息:服务器本身配置为侦听0.0.0.0上的sql,我还将防火墙设置为接受端口3306上的连接。
为清晰起见编辑:我知道我可以通过在服务器上授予本地计算机权限来解决这个问题,但是我希望能够通过ssh进行连接。

6pp0gazn

6pp0gazn1#

op解决方案。
ssh不起作用的原因是我需要使用一个本地开放端口,通过该端口连接到sql,然后将其转发到远程端口3306。另外,我需要通过localhost进行端口转发,而不是服务器地址(也就是说,改变 session.setPortForwardingL(3306, ServerIP, 3306); 行至 session.setPortForwardingL(some-open-port, "localhost", 3306); 以及 "jdbc:mysql://%s:3306/db_name""jdbc:mysql://%s:same-open-port/db_name" .

相关问题