Cannot connect to server port 23 with JSch - java

My JDK is 1.7.
import java.util.Properties;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class SSHClientTest {
public static void main(String[] args){
try {
String host = "192.168.1.233";
int port = 23;
String username = "root";
String password = "htnice";
// create JSch
JSch jSch = new JSch();
// get session
Session session = jSch.getSession(username, host, port);
session.setPassword(password);
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
// start connect
session.connect();
session.disconnect();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm getting the following exception:
Exception in thread "main" java.lang.NullPointerException
at com.jcraft.jsch.Session.start_discard(Session.java:1066)
at com.jcraft.jsch.Session.read(Session.java:937)
at com.jcraft.jsch.Session.connect(Session.java:309)
at com.jcraft.jsch.Session.connect(Session.java:183)
at SSHClientTest.main(SSHClientTest.java:26)
The same error with jsch-0.1.54 and jsch-0.1.55.
I can connect to the server by TTerm. The port is 23.

JSch is SSH client (port 22).
You cannot use it to connect to Telnet server (port 23).

Related

Connect to remote MySQL from my local machine through Jumpbox/Proxy

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

Java ssh2 connection to remote mysql server from eclipse

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 !

In my Java SFTP class, why am I getting this java.net.ConnectException?

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();

Java > JSch. How to get properties for SFTP connection from settings file?

I am using this code to download file from server:
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class Main {
public static void
main(String[] args) {
String host = "hostname";
String login = "username";
String password = "pass";
int port = 22;
String remoteDirectory = "directoryPath";
String localDirectory = "directoryPath";
Session session = null;
Channel channel = null;
ChannelSftp sftpChannel = null;
try{
JSch jsch = new JSch();
session = jsch.getSession(login, host, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp)channel;
sftpChannel.get(remoteDirectory, localDirectory);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
As you can see, username, password, host and port are hardcoded. I need to get these properties from settings.txt file which I have on my computer, but didn't succeed to make this possible.
settings.txt to the root of your project and use this code to load it:
Properties properites = new Properties();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream("/settings.txt");
properties.load(is);

commons-net is compatible with ssh-2.0 protocol

i have tried create a project with library commons.net for send via ftp some files. But i created a connection with my server i have received this error.
org.apache.commons.net.MalformedServerReplyException: Could not parse response code.
Server Reply: SSH-2.0-OpenSSH_5.3
i have followed this article for create my connection, and with official examples i've controlled article.
my java code here:
private void connect(String host, String user, String pwd) {
try{
ftp = new FTPSClient(false);
//ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host,22);//error is here
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}catch(Exception ex){
ex.printStackTrace();
}
}
I do not understand where I went wrong.
The FTPS protocol does not run over SSH. What you need is SFTP. For this you could look at the Jsch library
JSch jsch = new JSch();
Session session = jsch.getSession( user, host, port );
session.setConfig( "PreferredAuthentications", "password" );
session.setPassword( pass );
session.connect( FTP_TIMEOUT );
Channel channel = session.openChannel( "sftp" );
ChannelSftp sftp = ( ChannelSftp ) channel;
sftp.connect( FTP_TIMEOUT );
SFTP (file transfer running as an SSH stream over an SSH connection) is not the same as FTPS (FTP using SSL/TLS).
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class FTPConnectAndLoginDemo {
public static void main(String[] args) throws Exception {
String user = "username";
String host = "hostadress";
int port = 22;
String pass = "password";
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(pass);
session.connect();
System.out.println("Connection established.");
System.out.println("Creating SFTP Channel.");
}
try this instead hope this can help.The Session.setConfig ommits the hashcode check and allows user to connect to host.
Change the port to 21 to connect to FTP server instead of SFTP(port 22)

Categories

Resources