programing

Java의 SSH 터널을 통해 Mongo 데이터베이스에 연결

iphone6s 2023. 7. 1. 08:07
반응형

Java의 SSH 터널을 통해 Mongo 데이터베이스에 연결

고정(변경 사항을 반영하도록 코드 편집)

Java를 사용하여 SSH 터널을 통해 Mongo 데이터베이스에 연결하려고 합니다.

저는 Mongo 드라이버 3.0.2와 jcraft(JSch)를 사용하여 SSH 터널을 만들고 있습니다.제 생각은...

  • SSH를 통해 MongoDB 설치를 호스팅하는 시스템에 연결
  • 로컬 포트에서 원격 MongoDB 포트로 포트 전달 설정
  • 원격으로 MongoDB에 연결

내 코드는 다음과 같습니다.

// forwarding ports
private static final String LOCAL_HOST = "localhost";
private static final String REMOTE_HOST = "127.0.0.1";
private static final Integer LOCAL_PORT = 8988;
private static final Integer REMOTE_PORT = 27017; // Default mongodb port

// ssh connection info
private static final String SSH_USER = "<username>";
private static final String SSH_PASSWORD = "<password>";
private static final String SSH_HOST = "<remote host>";
private static final Integer SSH_PORT = 22;

private static Session sshSession;

public static void main(String[] args) {
try {
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = new JSch();
    sshSession = null;
    sshSession = jsch.getSession(SSH_USER, SSH_HOST, SSH_PORT);
    sshSession.setPassword(SSH_PASSWORD);
    sshSession.setConfig(config);
    sshSession.connect();
    sshSession.setPortForwardingL(LOCAL_PORT, REMOTE_HOST, REMOTE_PORT);

    MongoClient mongoClient = new MongoClient(LOCAL_HOST, LOCAL_PORT);
    mongoClient.setReadPreference(ReadPreference.nearest());
    MongoCursor<String> dbNames = mongoClient.listDatabaseNames().iterator();
    while (dbNames.hasNext()) {
    System.out.println(dbNames.next());
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    sshSession.delPortForwardingL(LOCAL_PORT);
    sshSession.disconnect();
}
}

이 코드를 실행하면, 하지 않는 EDIT: 작동합니다. SSH 서버에 연결하면 정상적으로 작동하지만 그 뒤에 있는 Mongo 데이터베이스에 연결하면 작동하지 않고 다음 오류가 반환됩니다.

INFO: Exception in monitor thread while connecting to server localhost:8988
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
    at com.mongodb.connection.SocketStream.read(SocketStream.java:88)
    at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:491)
    at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:221)
    at com.mongodb.connection.CommandHelper.receiveReply(CommandHelper.java:134)
    at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:121)
    at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
    at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83)
    at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
    at java.lang.Thread.run(Unknown Source)

다음과 같이 명령줄을 통해 이 작업을 수행해 보았습니다.

$ ssh <user>@<host> -p 22 -X -C
$ <enter requested password>
<user>@<host>$ mongo
<user>@<host>$ MongoDB shell version: 2.6.10
<user>@<host>$ connecting to: test

그래서 이것은 효과가 있는 것 같습니다.왜 자바 코드(거의 같은 일을 해야 하는)가 작동하지 않는지 모르겠습니다.

나는 그것을 작동시킬 수 있었습니다(포트를 "127.0.0.1"이 아닌 "localhost"로 전달하려고 시도하고 수정을 변경했습니다). 편집:서버가 127.0.0.1이 아닌 localhost에서 수신 중이었던 것 같습니다.

이 코드는 성공적으로 실행되지만 주요 문제는 당신의 몽고브가 중지되었다는 것입니다.몽고의 인스턴스가 실행 중인지 확인하십시오.

sudo systemctl status mongod

실행되지 않는 경우

sudo systemctl start mongod

언급URL : https://stackoverflow.com/questions/31161209/connecting-to-mongo-database-through-ssh-tunnel-in-java

반응형