I am using Java Eclipse on Windows, and have Mysql set up on Solaris 10. I have used JSch but it is not letting me to connect to Mysql database with root user.
I am getting the below error:
Connected
localhost:3306 -> xxx.xx.xxx.xxx:3306
Port Forwarded
java.sql.SQLException: Access denied for user: 'root#192.168.1.1' (Using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1309)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at ir.mnaeimabadi.hello.mysqltest.main(mysqltest.java:47)
Actually when in this line:
DriverManager.getConnection (url, dbuserName, dbpassword);
It is giving me the error.
This is overall code:
package ir.mnaeimabadi.hello;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.Connection;
public class mysqltest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int lport=3306;
String rhost="xxx.xx.xxx.xxx";
String host="xxx.xx.xxx.xxx";
int rport=3306;
String user="myusr";//ssh user
String password="mypass";//ssh pass
String dbuserName = "root";//mysql user
String dbpassword = "rootPass"; //mysql pass
String url = "jdbc:mysql://xxx.xx.xxx.xxx:";
String driverName="com.mysql.jdbc.Driver";
Connection conn = null;
Session session= null;
try{
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
System.out.println("Port Forwarded");
url = url+assinged_port+"/myDB";
//mysql database connectivity
Class.forName(driverName).newInstance();
conn = DriverManager.getConnection (url, dbuserName, dbpassword);
System.out.println ("Database connection established");
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(conn != null && !conn.isClosed()){
System.out.println("Closing Database Connection");
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(session !=null && session.isConnected()){
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
}
}
Related
Can I connect to remote Mysql via Jumpbox/proxy from my local machine.
I have a java application deployed in AWS machine(A) which has access and can connect to remote Mysql server(B). Now when I need to test my Java application locally I can not connect to Remote Mysql server(B).
So basically can my Java application connect to remote server from my local machine via AWS machine.
This way
Local Machine(java Application) ===> AWS machine(A)==> Mysql Server(B)
AWS Machine(A) can only be connected through SSH. :(
Can tunneling help here?
you can use JSch
http://www.jcraft.com/jsch/
an example of how to use it
package com.journaldev.java.ssh
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.Connection;
public class MySqlConnOverSSH {
/**
* Java Program to connect to the remote database through SSH using port forwarding
* #author Pankaj#JournalDev
* #throws SQLException
*/
public static void main(String[] args) throws SQLException {
int lport=5656;
String rhost="secure.journaldev.com";
String host="secure.journaldev.com";
int rport=3306;
String user="sshuser";
String password="sshpassword";
String dbuserName = "mysql";
String dbpassword = "mysql123";
String url = "jdbc:mysql://localhost:"+lport+"/mydb";
String driverName="com.mysql.jdbc.Driver";
Connection conn = null;
Session session= null;
try{
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName(driverName).newInstance();
conn = DriverManager.getConnection (url, dbuserName, dbpassword);
System.out.println ("Database connection established");
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null && !conn.isClosed()){
System.out.println("Closing Database Connection");
conn.close();
}
if(session !=null && session.isConnected()){
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
}
}
Reference:
https://www.journaldev.com/235/java-mysql-ssh-jsch-jdbc
We're running a server in our sports club, which requests (among other functionalities) our emails from t-online. Since a few weeks, the connection is refused most times.
I search around the questions and information on the telekom-page, but have not found any mistakes.
I made sure, the port and the address are correct: https://www.telekom.de/hilfe/festnetz-internet-tv/e-mail/e-mail-server-e-mail-protokolle-und-e-mail-einrichtung/posteingangsserver-und-postausgangsserver?samChecked=true
import java.util.Arrays;
import java.util.Properties;
import java.util.function.Consumer;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.SearchTerm;
public class EmailTestMain {
public static void main(String[] args) {
String username = "Email#t-online.de";
String password = "Password";
read(username, password, message -> {
try {
System.out.println(message.getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
}, Folder.READ_WRITE, null);
}
public static void read(final String username, final String password, Consumer<Message> messageConsumer,
int folderAction, SearchTerm searchTerm) {
final String host = "secureimap.t-online.de";
Properties props = new Properties();
props.setProperty("mail.imap.host", host);
props.setProperty("mail.imap.user", username);
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imap.ssl.tr ust", host); // JAVA truststore
props.setProperty("mail.imap.socketFactory", "993");
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.port", "993");
// Start SSL connection
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try (Store store = session.getStore("imap")) {
store.connect(host, username, password);
try (Folder emailFolder = store.getFolder("INBOX")) {
emailFolder.open(folderAction);
if (searchTerm != null) {
Arrays.stream(emailFolder.search(searchTerm)).forEach(messageConsumer::accept);
} else {
Arrays.stream(emailFolder.getMessages()).forEach(messageConsumer::accept);
}
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
The could should print out all subjects of the emails of the INBOX, but instead throw's an exception:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: secureimap.t-online.de, 993; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at de.bamberg.jugger.mail.EmailTestMain.read(EmailTestMain.java:55)
at de.bamberg.jugger.mail.EmailTestMain.main(EmailTestMain.java:21)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:218)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 4 more
I want to make a connection to the remote database ssh, in my java program, so I write a java code for this, I can ssh to the database server from my code but I can't access to the database, this is my out put which contains the error :
identity added
session created.
session connected.....
shell channel connected....
db Method...
try-catch
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at Main.connectToDB(Main.java:68)
at Main.main(Main.java:46)
Goodbye!
done
I run my .java class with this command ( I give both jsch and mysql-connector jar file, for running my class) and both jar files are in the folder that contains Main.java class
java -cp .:mysql-connector-java-5.0.7-bin.jar.:jsch-0.1.54.jar Main
and here is my code
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class Main {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "server-username";
String host = "server-Ip";
int port = 22;
String privateKey = "id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
connectToDB();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/DBname";
static final String USER = "username";
static final String PASS = "";
public static void connectToDB() {
System.out.println("db Method...");
Connection conn = null;
Statement stmt = null;
try{
System.out.println("try-catch");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,"");
System.out.println("hey!");
stmt = conn.createStatement();
String sql;
sql="SELECT * from test";
ResultSet rs = stmt.executeQuery(sql);
try (BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"))) {
while(rs.next()){
String name = rs.getString("name");
bw.write(name);
bw.newLine();
System.out.println(" name: " + name);
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
I confused , I think maybe I should put both jar files in the db-server ?
( Now there are in the javacode-server in the folder of java code)
Where I should put this jars,if I have to put them in the Database Server?
have been troubled by this for quite sometime, with reference to the code from here: http://www.journaldev.com/235/java-program-to-connect-to-remote-database-through-ssh-using-port-forwarding
have been trying, but still unable to get the connection. Here's my modified code:
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.Connection;
public class MySqlConnOverSSH {
/**
* Java Program to connect to remote database through SSH using port forwarding
* #throws SQLException
*/
public static void main(String[] args) throws SQLException {
int lport=5656;
String rhost="fictitious#germany.com";
String host="fictitious#germany.com";
int rport=3306;
String user="root";
String password="root";
String dbuserName = "root";
String dbpassword = "root";
String url = "jdbc:mysql://localhost:"+lport+"/test";
String driverName="com.mysql.jdbc.Driver";
Connection conn = null;
Session session= null;
try{
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assigned_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assigned_port+" -> "+rhost+":"+rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName(driverName).newInstance();
conn = DriverManager.getConnection (url, dbuserName, dbpassword);
System.out.println ("Database connection established");
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null && !conn.isClosed()){
System.out.println("Closing Database Connection");
conn.close();
}
if(session !=null && session.isConnected()){
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
}
and following is the error which i get:
Connected
localhost:5656 -> fictitious#germany.com:3306
Port Forwarded
java.sql.SQLInvalidAuthorizationSpecException: Could not connect: Access denied for user 'root'#'fictitious#germany.com' (using password: YES)
at org.mariadb.jdbc.internal.util.ExceptionMapper.get(ExceptionMapper.java:121)Closing SSH Connection
at org.mariadb.jdbc.internal.util.ExceptionMapper.throwException(ExceptionMapper.java:69)
at org.mariadb.jdbc.Driver.connect(Driver.java:110)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at myDB.MySqlConnOverSSH.main(MySqlConnOverSSH.java:50)
Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Could not connect: Access denied for user 'root'#'fictitious#germany.com' (using password: YES)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.authentication(AbstractConnectProtocol.java:433)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.handleConnectionPhases(AbstractConnectProtocol.java:397)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connect(AbstractConnectProtocol.java:318)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:630)
at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:580)
at org.mariadb.jdbc.Driver.connect(Driver.java:105)
... 3 more}
I am at Java:beginner level and trying to explore different ways to get this connection going. By the way, I am able to connect to the database using the given Username and password on SecureCRT, so the authorization error is kind of confusing. It would be great if someone could guide me in what I'm doing wrong and how it could be corrected. Thanks a ton in advance !
I am using a Java SFTP library Called JSch , and here is my code :
package client;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class SFTPCode_2 {
public SFTPCode_2() {
super();
}
public static void main (String[] args) {
SFTPCode_2 fileTransfer = new SFTPCode_2();
try {
JSch jsch = new JSch();
String host = "127.0.0.1";
int port = 22;
String user = "username";
Session sessionRead = jsch.getSession(user, host, port);
sessionRead.connect();
Session sessionWrite = jsch.getSession(user, host, port);
sessionWrite.connect();
ChannelSftp channelRead = (ChannelSftp)sessionRead.openChannel("sftp");
channelRead.connect();
ChannelSftp channelWrite = (ChannelSftp)sessionWrite.openChannel("sftp");
channelWrite.connect();
PipedInputStream pin = new PipedInputStream(2048);
PipedOutputStream pout = new PipedOutputStream(pin);
/* channelRead.rename("C:/Users/IBM_ADMIN/Desktop/Work/ConnectOne_Bancorp/Java_Work/SFTP_1/house.bmp",
"C:/Users/IBM_ADMIN/Desktop/Work/ConnectOne_Bancorp/Java_Work/SFTP_2/house.bmp"); */
channelRead.get("C:/Users/IBM_ADMIN/Desktop/Work/ConnectOne_Bancorp/Java_Work/SFTP_1/house.bmp", pout);
channelWrite.put(pin , "C:/Users/IBM_ADMIN/Desktop/Work/ConnectOne_Bancorp/Java_Work/SFTP_2/house.bmp");
channelRead.disconnect();
channelWrite.disconnect();
sessionRead.disconnect();
sessionWrite.disconnect();
} catch( JSchException e) {
e.printStackTrace(); }
catch (SftpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am trying to copy a file from one directory (within my local machine) to another, using the JSch library .
But it give me this error :
com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect
at com.jcraft.jsch.Util.createSocket(Util.java:349)
at com.jcraft.jsch.Session.connect(Session.java:215)
at com.jcraft.jsch.Session.connect(Session.java:183)
at client.SFTPCode_2.main(SFTPCode_2.java:43)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at com.jcraft.jsch.Util.createSocket(Util.java:343)
... 3 more
Process exited with exit code 0.
I tried adding Cygwin ( from link here ) but it still didn't work.
It's not clear what line is throwing the exception. Try to surround each Jsch action with try/catch, like so:
Session sessionRead = null;
try {
sessionRead = jsch.getSession(user, host, port);
} catch (JSchException e) {
System.out.println("Issue getting session.");
e.printStackTrace();
}
try {
sessionRead.connect(); // do you need to set properties first?
} catch (JSchException e) {
System.out.println("Issue connecting to session.");
e.printStackTrace();
}
For me, when I use Jsch, I had to add session properties to make the connection eg, on sessionRead.connect() .
sessionRead.setPassword("password");
sessionRead.setConfig("StrictHostKeyChecking", "no");
sessionRead.connect();