java在具有特定MySql主机的远程主机上通过SSH隧道连接到MySql数据库
我正在使用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 url中指定在哪里
# 1 楼答案
我知道这很旧,但localSSHUrl实际上是登录到SSH时使用的主机
简而言之,当您试图以本地用户身份连接到数据库时,这通常是“localhost”
许多示例都使用远程主机通过端口转发连接到SSH和数据库,但是如果您只有对数据库的本地访问权限,它将无法连接
# 2 楼答案
问题的根本原因是错误的端口转发方式:
而不是:
应该是的
连接现在运行正常