【发布时间】:2022-01-17 12:46:19
【问题描述】:
我正在尝试使用 Java 和 SSH 隧道连接到远程(AWS 服务器)MySQL 数据库。 当尝试使用 MySQL Workbench 连接到数据库时,它是成功的:
尝试使用 Java 代码连接到 MySQL 数据库时:
public class SQL {
private final String MYSQL_HOSTNAME_CONNECTION = EnvConf.getProperty("mysql.hostname");
private static final String sshUser = EnvConf.getProperty("ssh.username");
private static final String sshHost = EnvConf.getProperty("ssh.hostname");
public static void main(String[] args) throws JSchException {
establishSSHConnection();
getJDBCRemoteConnection();
}
private static void establishSSHConnection() {
JSch jsch = new JSch();
Session session = null;
try {
jsch.addIdentity(PATH_TO_PEM_FILE);
session = jsch.getSession(sshUser, sshHost);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
System.out.println("Connected!!!");
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
private static Connection getJDBCRemoteConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String dbName = "dbName"
String userName = "root";
String password = "password";
String hostname = "RDS_HOST_NAME";
String port = "3306";
String jdbcUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;
Connection con = DriverManager.getConnection(jdbcUrl);
return con;
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e.toString());
}
return null;
}
}
我收到下一条错误消息:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
===============================编辑=============== ================ 这是 SSH 隧道信息: ubuntu@SSH_HOSTNAME_STRING:22 并使用 Bastion PEM 文件进行身份验证。
【问题讨论】:
-
您不是通常通过 SSH 端口转发来访问 RDS 吗?是否需要
JSchCurious 如果您可以这样做而不是通过 Java 进行 SSH..? stackoverflow.com/questions/12699854/… -
@SMA 我没有尝试通过 SSH 进行端口转发,为什么使用 JSch 不是一个好的选择?
-
并不是说这不是一个好选择。只是好奇。您能否修改您的问题以展示您的 SSH 配置
-
你的意思是我工作台上的配置?
标签: java amazon-web-services jdbc ssh-tunnel