로컬 Java 응용 프로그램을 원격 mySQL 서버에 연결하려고합니다. 서버와 mySQL에 대한 셸 액세스 권한이 있지만 루트 액세스 권한은 없습니다.Java에서 SSH를 통해 원격으로 MySQL에 액세스
나는이 목표를 달성하는 것으로 보이는 온라인에서 발견 한 코드를 구현하려고 시도했다. 먼저 SSH를 서버에 넣은 다음 mySQL 데이터베이스에 액세스하려고 시도합니다. 그러나, 나는 다음과 같은 오류가 발생합니다 :
Jul 09, 2014 2:20:06 PM [myClassName] connect
SEVERE: null, message from server: "Host '[remoteHost]' is not allowed to connect to this MySQL server"
나는 기본적으로 MySQL의 원격 클라이언트 액세스를 허용하지 이해하지만 내가 이해하지 못하는 것은이 경우에 그 자체에게 자신의 MySQL 서버에 대한 액세스를 허용하지 않는 것 같다이다 . (즉, 오류 메시지의 [ "remoteHost"]는 액세스하려는 mySQL 서버를 호스팅하는 호스트와 동일한 호스트입니다.)
사용중인 코드 템플릿은 다음과 같습니다. 이 질문의 목적을 위해 모든 필드 (사용자, 패스, 호스트 등)를 템플릿에 그대로 두었습니다.
시스템 관리자에게 특별한 사용 권한을 요청해야합니까? 터미널을 통해 mySQL 서버에 액세스하는 데 문제가 없습니다. 미리 감사드립니다 모두
The Kahimyang Project (http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example)에 대한 크레딧.
import java.util.logging.Logger;
import com.jcraft.jsch.*;
import java.util.logging.Level;
public class MysqlManager {
// Logger
private final static Logger LOGGER =
Logger.getLogger(MysqlManager.class.getName());
public static void main(String args[]) {
MysqlManager mng = new MysqlManager();
mng.connect();
}
public void connect() {
//
int assigned_port;
final int local_port=3309;
// Remote host and port
final int remote_port=3306;
final String remote_host="kahimyang.info";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
Session session = jsch.getSession("user", remote_host, 22);
session.setPassword("ssh_password");
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
} catch (JSchException e) {
LOGGER.log(Level.SEVERE, e.getMessage()); return;
}
if (assigned_port == 0) {
LOGGER.log(Level.SEVERE, "Port forwarding failed !");
return;
}
// Database access credintials. Make sure this user has
// "connect" access to this database;
// these may be initialized somewhere else in your code.
final String database_user="user";
final String database_password="password";
final String database = "database";
// Build the database connection URL.
StringBuilder url =
new StringBuilder("jdbc:mysql://localhost:");
// use assigned_port to establish database connection
url.append(assigned_port).append ("/").append(database).append ("?user=").
append(database_user).append ("&password=").
append (database_password);
try {
Class.forName(
"com.mysql.jdbc.Driver").newInstance();
java.sql.Connection connection =
java.sql.DriverManager.getConnection(url.toString());
java.sql.DatabaseMetaData metadata = connection.getMetaData();
// Get all the tables and views
String[] tableType = {"TABLE", "VIEW"};
java.sql.ResultSet tables = metadata.getTables(null, null, "%", tableType);
String tableName;
while (tables.next()) {
tableName = tables.getString(3);
// Get the columns from this table
java.sql.ResultSet columns =
metadata.getColumns(null, tableName, null, null);
String columnName;
int dataType;
while (columns.next()) {
columnName = columns.getString(4);
dataType = columns.getInt(5);
// Your actual task;
}
}
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
java.sql.SQLException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
}
}