4

To connect to MongoDB from Java I use:

MongoClient mongoClient = new MongoClient("localhost", port);

And it works fine. Now I would like to connect to MongoDB which is on machine where I have to login by SSH. I try to use JSch for this, here is my code:

String host = "host";
String user = "user";
String password = "pass";
int port = 22;

int tunnelLocalPort = 3309;
String tunnelRemoteHost = "host";
int tunnelRemotePort = 3306;

JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
localUserInfo lui = new localUserInfo();
session.setUserInfo(lui);
session.connect();
session.setPortForwardingL(tunnelLocalPort, tunnelRemoteHost, tunnelRemotePort);

Everything looks fine, I can connect, but here is a problem:

MongoClient mongoClient = new MongoClient("localhost", 27020);
List<String> databaseNames = mongoClient.getDatabaseNames();
LOG.info("DB names=" + databaseNames);

And error is:

Aug 21, 2014 4:12:29 PM com.mongodb.DBTCPConnector initDirectConnection
Warnung: Exception executing isMaster command on localhost/127.0.0.1:27020
java.io.IOException: couldn't connect to [localhost/127.0.0.1:27020] bc:java.net.ConnectException: Connection refused: connect
    at com.mongodb.DBPort._open(DBPort.java:214)

Should I set something more to connect? How can I check from Java that program connects, when I check session.isConnected() output is true. When I use PuTTY everything works fine.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
tostao
  • 2,803
  • 4
  • 38
  • 61

1 Answers1

2

From above code I think you are tunneling a remote 3309 port to a local port on 3309 (and not 27020).

Per your code:

int tunnelLocalPort = 3309;
String tunnelRemoteHost = "host";
int tunnelRemotePort = 3306;
  1. Check the host and port of the remote host and map it accordingly.
  2. Set the local port to what you are listening in the code (27020).

Try the whole exercise without code first maybe:

  1. Tunnel the remote MongodDB server using PuTTY (or command line if you are on Linux).
  2. Connect via Mongo to the local port where you mapped the remote port.
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992