我正在使用 Jsch如下图上半部分所示,连接到远程mysql数据库,其中ssh主机与mysql主机不同:
下面是我用于 SSH 连接的代码:
private static void connectSSH() throws SQLException {
try {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
jsch.setLogger(new MyLogger());
session = jsch.getSession(sshUser, sshHost, 22);
jsch.addIdentity(SshKeyFilepath, sshPassword);
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.connect();
System.out.println("SSH Connected");
Class.forName(driverName).newInstance();
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("localhost:" + assinged_port + " -> " + sshHost + ":" + remotePort);
System.out.println("Port Forwarded");
} catch (Exception e) {
e.printStackTrace();
}
}
并最终使用以下代码连接到数据库:
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword);
我能够成功建立 SSH 连接,但执行在以下行时挂起:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword);
我已经通过命令行连接仔细检查了我的 SSH 和数据库凭据我可以使用
连接到数据库mysql -h host1 -u "myusername" -p"mypasswordhere"
我想问题可能是由于远程主机上的 mysql 主机不是 localhost 而是host1,我不知道在哪里指定jdbc 网址。
最佳答案
我知道这是旧的,但是 localSSHUrl 确实是您登录 SSH 时要使用的主机。
简而言之,当您尝试以本地用户身份连接到数据库时,这通常是“localhost”。
int assigned_port = session.setPortForwardingL(localPort, “localhost”, remotePort);
许多示例使用 remote_host 通过端口转发连接到 SSH 和数据库,但如果您只能在本地访问数据库,它将无法连接。
关于java - 在具有特定 mysql 主机的远程主机上使用 SSH 隧道连接到 MySql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34743398/