我无法通过ssh连接到mysql,我不知道为什么使用Java

时间:2014-11-12 17:26:42

标签: java mysql ssh tunnel

好的 - 所以我一直在研究这个问题已经有一段时间了(有时候还没有开始工作),而我几乎已经存在了,但还没有。我试图隧道到一个mysql数据库,并能够使用Jsch成功连接ssh。但是当我尝试连接到数据库时,它给了我一个“拒绝访问用户'usernamne'@'localhost'(使用密码:YES)

以下是以下代码:(当然我屏蔽了敏感信息)

public void connect(){
    String user = "user";
    String password = "password";
    String host = "host.com";
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = null;
        Properties info = new Properties();

        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);
        jsch.addIdentity("/Users/user/.ssh/id_rsa", password);

        session.setConfig("StrictHostKeyChecking", "no");
        System.out.println("Establishing Connection...");
        if(session.isConnected()){
            session.disconnect();
        }
        session.connect();
        conn = DriverManager.getConnection("jdbc:mysql://localhost:4417/dbname","dbuser", "dbpassword");
        System.out.print("Connection successful!" + "\n\n");
        System.out.print("Connection:" + conn + "\n\n");

        Statement stmt = conn.createStatement();
        ResultSet resultSet = stmt.executeQuery("SELECT * FROM TABLENAME limit 1");
        System.out.print(resultSet);
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (JSchException j){
        j.printStackTrace();
    }


}

我在这里读过其他帖子,但我没有找到解决问题的确切方法。我能够正确地ssh。而更有趣的是,如果我执行相同的过程command_line,它可以正常工作。所以我不知道为什么它在这里不起作用。

1 个答案:

答案 0 :(得分:0)

试试这个。它可能会帮助你。已在我的设置中测试过。请享用。 :)

在远程mysql db中创建db用户。

创建用户' myuser' @' clientip'通过'传递';

识别

创建用户' myuser' @'%'通过'传递';

识别

将所有on mydb。*授予' myuser' @' clientip';

将所有on mydb。*授予' myuser' @'%';

FLUSH PRIVILEGES;


ssh隧道的代码。

    int assigned_port;   
    final int local_port=8080;

    // Remote host and port
    final int remote_port=3306;
    final String remote_host="192.168.150.139";

    try {
        JSch jsch = new JSch(); 

        // Create SSH session.  Port 22 is your SSH port which
        // is open in your firewall setup.
        session = jsch.getSession("sshuser", remote_host, 22);
        session.setPassword("sshpassword");

        // 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 credentials.  Make sure this user has
    // "connect" access to this database;

    // these may be initialized somewhere else in your code.
    final String database_user="myuser";
    final String database_password="pass";
    final String database = "mydb";

    // 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");
        System.out.println(url.toString());
        java.sql.Connection connection =
                java.sql.DriverManager.getConnection(url.toString());

       String q="select * from customer";
       PreparedStatement ps=connection.prepareStatement(q);
       ResultSet rs= ps.executeQuery();
       while (rs.next()) {
        System.out.println(rs.getInt(1)+rs.getString(2));
    }


    } catch (ClassNotFoundException |
            java.sql.SQLException e) {
        LOGGER.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    }
    finally{
        session.disconnect();
    }