依赖配置pom
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
创建代理会话
/**
* 创建代理会话。会话使用结束后,别忘了调用closeSession以关闭会话。
*/
public static Session getSession(String sshIp,
String sshUser,
int sshPort,
String sshPwd,
String sshKeyPath) throws JSchException {
JSch jSch = new JSch();
if(sshKeyPath != null) jSch.addIdentity(sshKeyPath);
Session sesion = jSch.getSession(sshUser, sshIp, sshPort);
sesion.setPassword((sshPwd == null) ? "" : sshPwd);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
sesion.setConfig(config);
sesion.connect();
return sesion;
}
创建本地代理端口
/**
* 创建本地代理端口。
*/
public static int getPortForwardingL(Session sesion,
int loaclPort,
String mysqlIp,
int mysqlPort) throws JSchException {
return sesion.setPortForwardingL(loaclPort, mysqlIp, mysqlPort);
}
创建数据库连接
/**
* 创建数据库连接。
*/
public static Connection getConnection(String driver,
String localIp,
int portForwardingL,
String db,
String user,
String pwd) throws Exception {
String mysqlUrl = "jdbc:mysql://" + localIp + ":" + portForwardingL + "/" + db + "?characterEncoding=utf8&useSSL=false";
Class.forName(driver);
return DriverManager.getConnection(mysqlUrl, user, pwd);
}
调用示例代码
public static void main(String[] args) throws Exception {
// 代理服务器信息
String sshIp = "xxx.xxx.xxx.xxx";
String sshUser = "user";
int sshPort = 8585;
String sshPwd = "";
String sshKeyPath = "本地路径/id_rsa.rsa";
// 本机基本设置
int localPort = 12365;
String localIp = "localhost";
// 数据库JDBC连接信息
String mysqlIp = "xxx.xxx.xxx.xxx";
int mysqlPort = 3306;
String mysqlDriver = "com.mysql.jdbc.Driver";
String mysqlUser = "user";
String mysqlPwd = "pwd";
String mysqlDB = "db";
// 创建代理会话。会话使用结束后,别忘了调用closeSession以关闭会话。
Session session = SsshJdbcUtils.getSession(sshIp, sshUser, sshPort, sshPwd, sshKeyPath);
// 创建本地代理端口。
int portForwardingL = SsshJdbcUtils.getPortForwardingL(session, localPort, mysqlIp, mysqlPort);
// 创建数据库连接。
Connection connection = SsshJdbcUtils.getConnection(mysqlDriver, localIp, portForwardingL, mysqlDB, mysqlUser, mysqlPwd);
// 查询数据
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("show tables");
if(resultSet != null) {
while(resultSet.next()) {
String tableName = resultSet.getString(1);
System.err.println(tableName);
}
}
// 关闭相关连接
if(resultSet != null && !resultSet.isClosed()) resultSet.close();
if(statement != null && !statement.isClosed()) statement.close();
if(connection != null && !connection.isClosed()) connection.close();
if(session != null && session.isConnected()) session.disconnect();
}