LDAP Connection/ Apache DS / Java - java

i wanted to make an easy LDAP Connection with using Apache DS and Java, wanted to learn and play a bit with authentification. However, when i start using the my jar file, i always get this error message:
Setting up LDAP connection ...
LDAPException(resultCode=91 (connect error), errorMessage='An error occurred while attempting to resolve address 'ldap://localhost:10389':
UnknownHostException(Der angegebene Host ist unbekannt (ldap://localhost:10389)), ldapSDKVersion=6.0.0, revision=524c20f3bbcc0d83fb56b9e136a2fd3a7f60437d')
My apache DS LDAP server looks like this:
enter image description here
My Java code:
package ldap.test;
import java.security.GeneralSecurityException;
import javax.net.SocketFactory;
import com.unboundid.ldap.sdk.BindRequest;
import com.unboundid.ldap.sdk.BindResult;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldap.sdk.SimpleBindRequest;
import com.unboundid.util.ssl.SSLUtil;
import com.unboundid.util.ssl.TrustAllTrustManager;
public final class App2 {
// hostname of the ldap instance
public static final String HOSTNAME = "ldap://localhost:10389";
// port of the ldap instance
public static final int PORT = 10389;
public static final void main(String[] args)
{
// lazy hack
if ( args.length != 4 ) {
System.out.println("One or more parameters are missing!");
System.out.println("java -jar App2.jar $cn $sn $employeenumber $password");
System.out.println("Example: java -jar App2.jar Max Mustermann 1 1");
System.exit(1);
}
// Use no key manager, and trust all certificates. This should not be used in non-trivial code!
SSLUtil sslUtil = new SSLUtil(null, new TrustAllTrustManager());
SocketFactory socketFactory;
LDAPConnection ldapConnection = null;
try {
// Create the socket factory that will be used to make a secure
// connection to the server.
socketFactory = sslUtil.createSSLSocketFactory();
System.out.print("Setting up LDAP connection ... ");
ldapConnection = new LDAPConnection(socketFactory, HOSTNAME, PORT);
System.out.println("done!");
}
catch ( LDAPException ldapException ) {
System.err.println(ldapException);
System.exit(ldapException.getResultCode().intValue());
}
catch ( GeneralSecurityException exception ) {
System.err.println(exception);
System.exit(1);
}
// LDAP bindrequest and actual bind for DN search
System.out.print("Search DN for user with employeeNumber: " + args[2] + " ... ");
BindRequest ldapBind = new SimpleBindRequest(args[0], args[1]);
try {
// bind with technical user and password and search for DN
ldapConnection.bind(ldapBind);
String employeeNumber = args[2];
String userPassword = args[3];
Filter ldapFilter = Filter.createANDFilter(Filter.createEqualityFilter("number", employeeNumber));
SearchRequest searchReq = new SearchRequest("ou=users,o=Beispiel", SearchScope.SUB, ldapFilter, "dn");
SearchResult searchResult;
String foundDN = "none";
try
{
searchResult = ldapConnection.search(searchReq);
System.out.println("done!");
for ( SearchResultEntry entry : searchResult.getSearchEntries() )
{
foundDN = entry.getDN();
}
}
catch ( LDAPSearchException lse )
{
System.out.println("... error!");
// The search failed for some reason
searchResult = lse.getSearchResult();
ResultCode resultCode = lse.getResultCode();
System.out.println("Resultcode: " + resultCode);
String errorMessageFromServer = lse.getDiagnosticMessage();
System.out.println("Error message from server: " + errorMessageFromServer);
}
// now check for the foundDN if the given password is correct
if ( !foundDN.equals("none") ) {
System.out.println("Found DN for user with EmployeeNumber: " + employeeNumber + " => " + foundDN);
System.out.println("Now checking if password for user is correct!");
BindRequest userBindReq = new SimpleBindRequest(foundDN, userPassword);
BindResult userBindRes = ldapConnection.bind(userBindReq);
System.out.println("Result: " + userBindRes);
}
else {
System.out.println("No DN found for user with EmployeeNumber: " + employeeNumber);
}
}
catch ( LDAPException ldapException ) {
System.err.println(ldapException);
System.exit(ldapException.getResultCode().intValue());
}
finally {
// Close ldap connection
ldapConnection.close();
}
}
}
No idea why i cant connect to the server...
-----Edit--------
When i change the HOSTNAME to localhost, i get the following error message:
Setting up LDAP connection ... LDAPException(resultCode=91 (connect error),
errorMessage='An error occurred while attempting to connect to server localhost:10389: IOException(LDAPException(resultCode=91 (connect error),
errorMessage='An error occurred while attempting to establish a connection to server localhost/127.0.0.1:10389: SSLException(Unsupported or unrecognized SSL message),
ldapSDKVersion=6.0.0, revision=524c20f3bbcc0d83fb56b9e136a2fd3a7f60437d'))')
Well the good thing is that he can find localhost, but he cant connect to the server

I faced a similar issue, and the problem was solved by calling the LDAPConnection constructor with only two arguments ("localhost",10389). Could you check if this resolves your issue too?
Ofcourse, you should also remove the "ldap//:" prefix too!

Related

Connection between Java and MySql

I am trying to make a connection between Java and my data base. I am using Eclipse and xampp. I am almost convinced that I have good config of Eclipse and xampp, but maybe I missed something. I searched a lot on the Internet, but I have not found the solution.
My error are:
SQLException: Could not create a connection to database server. Attempted to reconnect 3 times. Giving up.
SQLState: 08001
VendorError: 0
Xampp -
Xampp config
Eclipse -
I have jar files in the workspace folder.
Eclipse config
phpmyadmin -
I do not need a password to log into localhost/phpmyadmin and I have only one record in DB.
Code
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBC2 {
static String daneZBazy;
static String polaczenieURL = "jdbc:mysql://localhost:3306/heroes.db?
autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "root";
public static void main(String[] args) {
// Question to DB
String query = "Select * FROM heroestab";
Connection conn = null;
try {
// Connection parameters
conn = DriverManager.getConnection(polaczenieURL, login, password);
// MySQL Driver
Class.forName("com.mysql.jdbc.Driver");
// Start question to DB
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
wyswietlDaneZBazy(rs);
}
conn.close();
}
//throws exception
catch (ClassNotFoundException wyjatek) {
System.out.println("Driver error");
}
catch (SQLException wyjatek) {
wyjatek.printStackTrace();
System.out.println("Login problem. Check, username, password, DB name, IP adress");
System.out.println("SQLException: " + wyjatek.getMessage());
System.out.println("SQLState: " + wyjatek.getSQLState());
System.out.println("VendorError: " + wyjatek.getErrorCode());
}
}
static void wyswietlDaneZBazy(ResultSet rs) {
try {
daneZBazy = rs.getString(1);
System.out.println("\n" + daneZBazy + " ");
daneZBazy = rs.getString(2);
System.out.println(daneZBazy + " ");
daneZBazy = rs.getString(3);
System.out.println(daneZBazy);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Please verify that both the username and password are correct.
I need the full stack trace from:
wyjatek.printStackTrace();
If the username (root) and password are incorrect, you will see the below line in your stacktrace:
Access denied for user 'root'#'localhost' (using password: YES)
If I remember correctly, with default xampp config, you can try this:
user: root
password: [blank]
static String login = "root";
static String password = "";
I can see my databases useing cmd:
C:\xampp\mysql\bin > mysql -u root -p
Enter
show databases ; and then I can see all databases which I have on localhost. When i
chose heroes and I can select * from heroes ;
Picture:
Database cmd

Login success on FTP over explicit SSL/TLS but unable to browse the files

I have been asked to make the secure FTP Server connection. FTP over explicit TLS/SSL. In order to achieve this, I have added a below line in the existing implementation. This is my FTPClient lib - it.sauronsoftware.ftp4j - version 1.6.1
ftpClient.setSecurity(FTPClient.SECURITY_FTPES);
// Existing code
ftpClient.setConnector(new HTTPTunnelConnector(proxyHost, proxyPort));
ftpClient.connect(getFtpHost(), getFtpPort());
ftpClient.login(getUsername(), getPassword());
ftpClient.setAutoNoopTimeout(30000);
When I deployed the code on JBOSS 5.1, I am getting successful connection, but I am unable to list the files in the root directory. we only have permission to access the root directory.
On the other hand, I have written a standalone client (java main program) - through which I can print the files present at FTP location, by this way I have ensured the secure connection and the files availability at FTP location. Here, I have used the
My problem is, when I make a secure connection through the deployed application I am getting the unable to locate any files at remote location. ie: FTPFiles.length is 0
Any help would be much appreciated, thank you!
Adding few more logs and info,
Normal Flow without FTPES security parameter added (current Implementation)
printing ftpClient.serverStatus()
msg: Status of 'FTP Service'
msg: Connected from ec2-xyz
msg: Logged in as <user>
msg: TYPE: BINARY, STRUcture: File, Mode: Stream
msg: Total bytes transferred for session: 10511
msg: No data connection
msg: End of status
printing ftpClient.serverStatus() With FTPES added
msg: Status of 'FTP Service'
msg: Connected from ec2-xyz
msg: Logged in as <user>
msg: TYPE: ASCII, STRUcture: File, Mode: Stream
msg: No data connection
msg: End of status
Few questions which I need to know answers (may be that give a lead to fix):
Here, TYPE: BINARY is changed to ASCII and can someone tell how to modify back to BINARY? Note tehre is no explicit setting made, got changed post FTPES set
Is this issue related to proxy / port. if so - I wont be able to provide those information.
As of now, I am testing with same proxy used which is used in the application.
Is there any certificates to be imported to get files viewed / downloaded.
Found this on net which is exactly same as my issue, http://www.proftpd.org/docs/howto/TLS.html ( search for -"I can login using FTPS, but I cannot see any directories. Why not?") but I need to explain my third party to make the required change... what should I tell?
stand alone client code
import it.sauronsoftware.ftp4j.*;
import javax.net.ssl.*;
import java.io.File;
import java.security.*;
import java.util.List;
public class FTPWithSSL {
private static FTPClient ftpClient;
private static FTPConfig ftpConfig;
private DailyFTPConfig config;
public static void main(String args[]) throws Exception {
ftpConfig = new FTPConfig("username", "password", "FTPServer.net", 21, setupConnector());
FTPDownloader ftpDownloader = new FTPDownloader(ftpConfig, new FTPDownloadController() {
#Override
public List<FTPFile> download(FTPClient ftpClient) throws Exception {
downloadFile(ftpClient);
System.out.println("download success");
return null;
}
});
try {
openConnection();
List<FTPFile> ftpFileList = ftpDownloader.download();
closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void openConnection() throws Exception {
System.out.println("OpenConnection method");
if (ftpClient == null) {
ftpClient = new FTPClient();
// Even if the below line is commented, the code works fine
ftpClient.setSSLSocketFactory(getSSLSocketFactory());
System.out.println("setting FTPES here");
ftpClient.setSecurity(FTPClient.SECURITY_FTPES);
ftpClient.setConnector(ftpConfig.getConnector());
ftpClient.connect(ftpConfig.getFtpHost(), ftpConfig.getFtpPort());
ftpClient.login(ftpConfig.getUsername(), ftpConfig.getPassword());
ftpClient.setAutoNoopTimeout(30000);
System.out.println("ftpClient.isConnected() " + ftpClient.isConnected());
}
}
private static SSLSocketFactory getSSLSocketFactory() throws Exception {
TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
return sslSocketFactory;
}
private static void closeConnection() throws Exception {
System.out.println("ftpClient.serverStatus() -- ");
for (String serverStatus : ftpClient.serverStatus()) {
System.out.println(" msg: " + serverStatus);
}
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.disconnect(false);
}
}
private static void downloadFile(FTPClient ftpClient) throws Exception {
System.out.println("ftpsClient.currentDirectory() " + ftpClient.currentDirectory());
FTPFile[] ftpFile = ftpClient.list();
System.out.println("Name " + ftpFile[0].getName());
System.out.println("Link " + ftpFile[0].getLink());
System.out.println("Modified Date " + ftpFile[0].getModifiedDate());
String[] listnames = ftpClient.listNames();
System.out.println("ftpsClient.listNames() " +listnames);
System.out.println("ftpsClient.currentDirectory() " + ftpClient.list());
File file = new File( "C:\\opt\\copycat\\a1234.zip");
System.out.println("Downloading File: [" + file.getName() + "] has started.");
ftpClient.download("a1234.zip", file);
System.out.println("Downloading File: has Completed");
}
private static FTPConnector setupConnector() {
FTPConnector connector = new DirectConnector();
String proxyHost = "amazonaws.com";
if (proxyHost != null) {
System.out.println("proxy host NOT NULL");
int proxyPort = Integer.parseInt("123");
connector = new HTTPTunnelConnector(proxyHost, proxyPort);
}
return connector;
}
}
Finally, I am able to make the secure connection and able to download the latest files from FTP server using FTPES (FTP over explicit TLS/SSL).
I have made only 2 line code changes (below), in the actual implementation. earlier it was having the list() method to get the files from FTP server, and its return type is FTPFile[]
This is the code changes which I made, and other line of codes are modified / removed.
ftpClient.setSecurity(FTPClient.SECURITY_FTPES);
// get the FTP connection
String[] fileNames = ftpClient.listNames();
// Exisitng implementation
FTPFile[] ftpFiles = ftpClient.list("*.zip");
// after that there is an implementation for getting the latest files using the Comparator<FTPFile>
There was an issue with the LIST command's output, ie: LIST *.zip is not giving the correct output (I guess)

what is 'proxy.mycompany1.local'

I just started working in Java networking protocols. I am trying to connect to the internet using my proxy server. When I see the post at 'https://www.tutorialspoint.com/javaexamples/net_poxy.htm', they set the http.proxyHost property to 'proxy.mycompany1.local'. I know I can set this to my proxy server IP, but I am curious to know why my program still works, even though I set it to some random string like "abcd".
A. What does 'proxy.mycompany1.local" stand for?
B. How come my program works, even though I set the http.proxyHost" to "abcd"?
Following is my working program:
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URL;
public class TestProxy {
public static void main(String s[]) throws Exception {
try {
System.setProperty("http.proxyHost", "abcd");
System.setProperty("http.proxyPort", "8080");
URL u = new URL("http://www.google.com");
HttpURLConnection con = (HttpURLConnection) u.openConnection();
System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
} catch (Exception e) {
e.printStackTrace();
System.out.println(false);
}
Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI("http://www.google.com")).iterator().next();
System.out.println("proxy Type : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}
This is the output:
200 : OK
proxy Type : HTTP
proxy hostname : abcd
proxy port : 8080
First of all, according System Properties tutorial.
Warning: Changing system properties is potentially dangerous and
should be done with discretion. Many system properties are not reread
after start-up and are there for informational purposes. Changing some
properties may have unexpected side-effects.
And my experience say you can get unpleasant issues on your system when you change *.proxyHost properties. So I highly wouldn't recommend you to change system properties for this task.
Much better use something like:
//Proxy instance, proxy ip = 127.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
and authorisation on proxy:
Authenticator authenticator = new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user",
"mypassword".toCharArray());
}
};
Authenticator.setDefault(authenticator);
Now return to main questions:
A. 'proxy.mycompany1.local" is just example. You can use any hostname
B. Class URL uses java.net.PlainSocketImpl class via Socket. It tries to resolve proxy hostname 'abcd', swallow error and go to google directly. Just try to play with this code:
import java.net.*;
import java.io.*;
public class RequestURI {
public static void main(String[] args) {
int port = 8181;
long startTime = System.currentTimeMillis();
try {
// System.getProperties().setProperty("http.proxyHost", "abcd");
// System.getProperties().setProperty("http.proxyPort", Integer.toString(port));
URL url = new URL("http://google.com");
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
int resp = uc.getResponseCode();
if (resp != 200) {
throw new RuntimeException("Failed: Fragment is being passed as part of the RequestURI");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Run time in ms ="+ (System.currentTimeMillis() - startTime));
}
}
You can see run time is bigger when you uncomment section with setProperty. Unsuccessful attempt to resolve hostname increases execution time.
First of all, proxy.mycompany1.local is just a host name, it is a sample, it is nothing special.
I tried your code in a non proxied network, and it worked as you described. I guess that url.openConnection() method ignores proxy settings, because if you manage your own proxy and use url.openConnection(proxy), then it fails with a java.net.UnknownHostException.
Here you are with a piece of code that fails:
SocketAddress addr = new InetSocketAddress("abcd", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
URL url = new URL("http://google.com");
URLConnection conn = url.openConnection(proxy);
InputStream in = conn.getInputStream();
in.close();
You can read more about Java Networking and Proxies.

"The Transport Protocol thread failed" – "The socket is EOF" with J2SSH connection using Java

I am trying to establish an SSH connection through my Java code, but getting below exception .. I tested my connection through Putty/Winscp tools and it works fine. The problem is with my Java code...
SEVERE: The Transport Protocol thread failed
java.io.IOException: The socket is EOF
at com.sshtools.j2ssh.transport.TransportProtocolInputStream.readBufferedData(Unknown Source)
at com.sshtools.j2ssh.transport.TransportProtocolInputStream.readMessage(Unknown Source)
at com.sshtools.j2ssh.transport.TransportProtocolCommon.readMessage(Unknown Source)
at com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.performClientExchange(Unknown Source)
at com.sshtools.j2ssh.transport.TransportProtocolClient.performKeyExchange(Unknown Source)
at com.sshtools.j2ssh.transport.TransportProtocolCommon.beginKeyExchange(Unknown Source)
at com.sshtools.j2ssh.transport.TransportProtocolCommon.onMsgKexInit(Unknown Source)
at com.sshtools.j2ssh.transport.TransportProtocolCommon.startBinaryPacketProtocol(Unknown Source)
at com.sshtools.j2ssh.transport.TransportProtocolCommon.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Below is my piece of Java code to establish the connection
public class MySSHClient {
static SshClient ssh = null;
static SshConnectionProperties properties = null;
SessionChannelClient session = null;
private static void MySSHClient(String hostName, String userName, String passwd )
{
try
{
// Make a client connection
ssh = new SshClient();
properties = new SshConnectionProperties();
properties.setHost("192.168.1.175");
// Connect to the host
ssh.connect(properties, new IgnoreHostKeyVerification());
// Create a password authentication instance
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername("root");
pwd.setPassword("123456");
// Try the authentication
int result = ssh.authenticate(pwd);
// Evaluate the result
if (result==AuthenticationProtocolState.COMPLETE) {
System.out.println("Connection Authenticated");
}
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
}//end of method.
public String execCmd(String cmd)
{
String theOutput = "";
try
{
// The connection is authenticated we can now do some real work!
session = ssh.openSessionChannel();
if ( session.executeCommand(cmd) )
{
IOStreamConnector output = new IOStreamConnector();
java.io.ByteArrayOutputStream bos = new
java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos );
session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
theOutput = bos.toString();
}
//else
//throw Exception("Failed to execute command : " + cmd);
//System.out.println("Failed to execute command : " + cmd);
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
return theOutput;
}
public static void main(String[] args){
MySSHClient(null, null, null);
}
Motivation
I stumbled across this question and answers while investigating the error in question java.io.IOException: The socket is EOF. Because changing the code to use some other SSH Java library is not immediately possible in my case and the stated explanation by #a3.14_Infinity was not detailed enough for me, I'd like to add my take on it.
java.io.IOException: The socket is EOF - Why?
Because this exception is not very helpful, I first tried Wireshark to see what's going on over the wire, but to no avail. So I configured the sshd_config (OpenSSH 6.9) to log on DEBUG3 level and got the answer in the /var/log/auth.log file of my test machine. It stated a fatal error while trying to negotiate the key exchange algorithm with the SSH client (the Java SSH library).
Because the SSH server and client could not agree on a mutual key exchange algorithm the OpenSSH server terminates the connection to the client. In consequence, the Java SSH library code throws the exception.
But why does it happen?
The sshtools.j2ssh (sshtools : j2ssh-core : 0.2.9) library code is pretty old and discontinued. Starting with OpenSSH 6.7 (released October, 2014) default ciphers and MAC have been altered to remove unsafe algorithms which includes the blowfish-cbc cipher. And with OpenSSH 6.9 (released June, 2015) the support for the 1024-bit diffie-hellman-group1-sha1 key exchange is disabled by default.
When you still use the prehistoric SSH Tools j2ssh library (God forbid) connecting to a newer OpenSSH server you will get the described error. The library code only offers the diffie-hellman-group1-sha1 key exchange algorithm to the OpenSSH server which it does not support by default. Thus, a secure connection cannot be established.
Cannot change the code?
If moving to another Java SSH library is not immediately possible (my case) then you can re-enable the disabled diffie-hellman-group1-sha1 key exchange algorithm in the OpenSSH's server config file sshd_config. For example like this.
Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm#openssh.com,aes256-gcm#openssh.com,chacha20-poly1305#openssh.com,blowfish-cbc
KexAlgorithms diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,curve25519-sha256#libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
But let me be clear on this. The diffie-hellman-group1-sha1 key exchange algorithm as well as the blowfish-cbc cipher are turned off by default because they are insecure. Reenabling them should only be a temporary measure until you can replace this obsolete Java SSH library.
Finally, I like to point out that the suggested Java Secure Channel (JSch) library in other answers is discontinued. So, you might want to consider sshj or even ssh2j-maverick instead.
Edit: I was wrong, the Java Secure Channel JSch library is alive (JSCH 0.1.54 was released on 2016-09-03 on MavenCentral) and certainly worth your consideration. Alternatively, you may want to consider also sshj or ssh2j-maverick.
Addendum: Migration
To keep the migration effort for the sshtools.j2ssh (sshtools : j2ssh-core : 0.2.9) library minimal I looked at the commercial legacy SSH client library from SSHTOOLS (version 1.7.1). This allowed to keep the existing library integration code with few minor changes regarding library API and exception handling. Thus, if you do not want to restart from scratch then biting the bullet and sticking with SSHTOOLS is probably your best option. Finally, to gauge the migration effort I first replaced the library with SSHTOOLS' open source library ssh2j-maverick which almost has the same API as its latest commercial version (version 1.7.1).
This error ("The Transport Protocol thread failed. java.io.IOException: The socket is EOF”) occurs when j2ssh.jar file is not compatible with current SSH version of SFTP server.
You can try using Java Secure Channel (JSch) from here.
Courtesy: http://techydiary.com/the-transport-protocol-thread-failed-java-io-ioexception-the-socket-is-eof/
The following sample Code may help you,
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHClient {
/**
* Constant EXCUTE_CHANNEL
*/
public static final String EXCUTE_CHANNEL = "exec";
/**
* Constant STRICT_KEY_CHECKING
*/
public static final String STRICT_KEY_CHECKING = "StrictHostKeyChecking";
/** Name/ip of the remote machine/device **/
private String host;
private String userName;
private String password;
/**
* This method used to initilze user and host
*
* #param userName
* #param password
* #param host
*/
public SSHClient(String userName,String password, String host) {
super();
this.userName = userName;
this.password = password;
this.host = host;
}
/**
* This method used to execute commands remotly by using SSHV2
*
* #param host
* #param username
* #param password
* #param command
* #return
*/
public String executeCommand(String command) {
StringBuilder log = new StringBuilder();
String response = null;
Channel channel = null;
Session session = null;
try {
JSch jsch = new JSch();
JSch.setConfig(STRICT_KEY_CHECKING, Constants.NO);
session = jsch.getSession(userName, host, 22);
// If two machines have SSH passwordless logins setup, the following
// line is not needed:
session.setPassword(password);
session.connect();
channel = session.openChannel(EXCUTE_CHANNEL);
((ChannelExec) channel).setCommand(command);
// channel.setInputStream(System.in);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
response = IOUtils.toString(in);
} catch (Exception ex) {
//handle exception
} finally {
try {
if (session != null) {
session.disconnect();
}
} catch (Exception ex) {
//handle exception
}
try {
if (channel != null) {
channel.disconnect();
}
} catch (Exception ex) {
//handle exception
}
}
System.ou.println( "Response received :"+ response));
return response;
}
}
Here is the working code reused from some google source -
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.StreamGobbler;
Connection conn = new Connection(server);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(user_id, password);
System.out.println("Is server - " + server + " Authenticated? " + isAuthenticated);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
ch.ethz.ssh2.Session sess = conn.openSession();
String new_commands = "";
for (int i = 0; i < commands.size(); i++) {
new_commands = new_commands + commands.get(i) + "\n";
}
System.out.println("The command executed is: " + new_commands);
sess.requestDumbPTY();
sess.execCommand(new_commands);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
InputStream errStrm = new StreamGobbler(sess.getStderr());
BufferedReader stderrRdr = new BufferedReader(new InputStreamReader(errStrm));
sess.getStdin().write("EXIT\n".getBytes());
System.out.println("the output of the command is");
while (true) {
String line_out = br.readLine();
if (line_out == null) {
break;
} else {
System.out.println(line_out);
output_logs.add(line_out);
}
}
while (true) {
String line_error = stderrRdr.readLine();
if (line_error == null) {
break;
} else {
System.out.println(line_error);
output_logs.add(line_error);
}
}
output_logs.add("Exit Code:" + sess.getExitStatus());
System.out.println("ExitCode: " + sess.getExitSignal());
sess.close();
conn.close();
found a simple solution on the OS:
comment out the Cipher line in /etc/ssh/sshd_config
and run service sshd restart

Why the java code compile correctly and throw out error while calling the class with passing parameter?

I have been following this url
http://docs.oracle.com/javaee/1.4/tutorial/doc/JMS5.html
And i have created the connectionfactory, queue and topic. I have been using the source code given on above url to connect the JMS. While i run the following code, there is no any compiling error but the code doesnot run while passing the parameter on it.
import javax.jms.*;
import javax.naming.*;
public class SimpleProducer {
public static void main(String[] args) {
final int NUM_MSGS;
if ((args.length < 1) || (args.length > 2)) {
System.out.println("Program takes one or two arguments: " +
"<dest_name> [<number-of-messages>]");
System.exit(1);
}
String destName = new String(args[0]);
System.out.println("Destination name is " + destName);
if (args.length == 2) {
NUM_MSGS = (new Integer(args[1])).intValue();
} else {
NUM_MSGS = 1;
}
Context jndiContext = null;
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
System.out.println("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination. If either
* does not exist, exit. If you look up a
* TopicConnectionFactory or a QueueConnectionFactory,
* program behavior is the same.
*/
ConnectionFactory connectionFactory = null;
Destination dest = null;
try {
connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/ConnectionFactory");
dest = (Destination) jndiContext.lookup(destName);
} catch (Exception e) {
System.out.println("JNDI API lookup failed: " + e.toString());
e.printStackTrace();
System.exit(1);
}
/*
* Create connection.
* Create session from connection; false means session is
* not transacted.
* Create producer and text message.
* Send messages, varying text slightly.
* Send end-of-messages message.
* Finally, close connection.
*/
Connection connection = null;
MessageProducer producer = null;
try {
connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(dest);
TextMessage message = session.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message " + (i + 1));
System.out.println("Sending message: " + message.getText());
producer.send(message);
}
/*
* Send a non-text control message indicating end of
* messages.
*/
producer.send(session.createMessage());
} catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
When i run the code using eclipse and passing the parameter for the class i.e paramater myqueue and 3. It returns the following error.
Destination name is jms/Queue
JNDI API lookup failed: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at SimpleProducer.main(SimpleProducer.java:53)
Do i have to configure any thing in jndi.properties config file in glassfish server. Currently the jndi.properties final has
java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory
The URL you provided has a section "Creating JMS Administered Objects". You should follow those steps to properly configure your testing environment.
The tutorial teaches you how to configure that using a web interface, but you should be able to find the config files on the server to apply the same data to your Eclipse environment later.
Glassfish has a similar web console. You should be able to create Connection Factory in a similar way as the tutorial teaches.

Categories