Unable to connect ot remote DB with ssh tunnel

89 Views Asked by At

I'm trying to connect to my remote DB with a ssh tunnel, I'm able to achieve this through my DB manager easily but when i try replicating it with my code I'm facing issues,

my SSH connection

   public void afterPropertiesSet() throws Exception {
        Session session = null;
        try {
            session = new JSch().getSession("********","1x.xx.xx.xx");
            session.setPassword("*********");
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            session.setPortForwardingL(1521,"xx.xx.yy.yy",1521);
            System.out.println("port forwarding completed");
            Class.forName("oracle.jdbc.OracleDriver");
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//xx.xx.yy.yy:1521/db","********","********");
            System.out.println(conn.getMetaData().getUserName());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(session!=null) {
                session.disconnect();
            }
        }
    }

when i run it i keep getting

java.sql.SQLException: ORA-12541: Cannot connect. No listener at host xx.xx.yy.yy port 1521. (CONNECTION_ID=wIOJk+zFTYCI4FR7XNsHew==)

if i change the port to something else i get this (like changing to 1520 [keeping host same])

Caused by: oracle.net.ns.NetException: ORA-12541: Cannot connect. No listener at host localhost port 1520. (CONNECTION_ID=On8tBIXKQCu40izLoOLsRg==)

and when i try changing the driver host to localhost (or actual machine ip) i get this(i.e changing to both localhost and 127.0.0.1; maintaining the port)

Caused by: oracle.net.ns.NetException: ORA-12541: Cannot connect. No listener at host localhost port 1520. (CONNECTION_ID=o8/105qIRG+N9zBuyiaMZg==)
1

There are 1 best solutions below

5
Martin Prikryl On

Starting the forwarding won't magically make the remote IP (xx.xx.yy.yy) available.

You need to connect to the local forwarded port (localhost:1521).