SFTP in Java

There are several free libraries to perform connections via FTP in Java (such as Sun SDK, Apache Commons Net, …). However, these ones doesn’t support SSH connections. In order to use this kind of connections, few alternatives can be found.

I’m using J2SSH project which is an abandoned software which later evolved in J2SSH-Maverick commercial package.

Connecting a server through ip address and port 22 with user/password authentication can be done as follows.

import java.util.List;

import com.sshtools.j2ssh.SftpClient;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.sftp.SftpFile;

private static final String LOGS_APPS = "/logs";
private static final String USERNAME = "user";
private static final String PASSWORD = "pass";

// Connect
SshClient ssh = new SshClient();
ssh.connect("127.0.0.1", 22, new AlwaysAllowingConsoleKnownHostsKeyVerification());

// Authenticate
PasswordAuthenticationClient passwordAuthenticationClient =
    new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(USERNAME);
passwordAuthenticationClient.setPassword(PASSWORD);

int result = ssh.authenticate(passwordAuthenticationClient);
if(result != AuthenticationProtocolState.COMPLETE){
     throw new Exception("Login failed");
}

// Open the SFTP channel
SftpClient client = ssh.openSftpClient();

// List log directory
client.cd(LOGS_APPS);
List ls = client.ls();

...

I’ve also included AlwaysAllowingConsoleKnownHostsKeyVerification class in order to avoid user interaction required to accept connections to unknown hosts.

import com.sshtools.j2ssh.transport.ConsoleKnownHostsKeyVerification;
import com.sshtools.j2ssh.transport.InvalidHostFileException;
import com.sshtools.j2ssh.transport.publickey.SshPublicKey; 

public class AlwaysAllowingConsoleKnownHostsKeyVerification extends
        ConsoleKnownHostsKeyVerification { 

    public AlwaysAllowingConsoleKnownHostsKeyVerification()
            throws InvalidHostFileException {
        super();
        // Don't not do anything else
    } 

    @Override
    public void onHostKeyMismatch(String s, SshPublicKey sshpublickey,
            SshPublicKey sshpublickey1) {
        try
        {
            System.out.println("The host key supplied by " + s + " is: " +
                sshpublickey1.getFingerprint());
            System.out.println("The current allowed key for " + s + " is: " +
                sshpublickey.getFingerprint());
            System.out.println("Using Custom Key verification, " +
                "allowing to pass through");
            allowHost(s, sshpublickey, false);
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
    } 

    @Override
    public void onUnknownHost(String s, SshPublicKey sshpublickey) {
        try
        {
            System.out.println("The host " + s +
                " is currently unknown to the system");
            System.out.println("The host key fingerprint is: " +
                sshpublickey.getFingerprint());
            System.out.println("Using Custom Key verification, " +
                "allowing to pass through~~~");
            allowHost(s, sshpublickey, false);
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
    } 

}
  • FTPS is ftp over a SSL (secure sockets layer) connection.
  • SFTP is not ftp but SCP (secure copy) commands (or similar) over a SSH2 (secure shell) connection.

In j2ssh 0.2.9 com.sshtools.j2ssh.transport.IgnoreHostKeyVerification class can be used to perform the same operation described in the given example ( AlwaysAllowingConsoleKnownHostsKeyVerification)

About these ads

15 comentarios en “SFTP in Java

  1. You are right, surprisingly there are only a few options…

    Your solutions is for “SFTP” (FTP over SSH), but if you would want to implement an “FTPS” client (FTP over SSL), the best option is Apache Commons Net, but changing the Socket Factory (it has a method for stablising it).

    P.S: Great blog! ;-)

  2. Hi,

    I would like to know the server setup. For me the FTP server is behind a Firewall. I need to do a SSH connection to firewall and then do a FTP connect. I am using setProxyHost setProxyUsername and setProxyPassword. But I am getting connection refused reply always. I am using PasswordAuthenticationClient for Host password authentication.

    The below is the code

    public void verifySSHConnection() throws IOException {
    SshClient client = new SshClient();
    SshConnectionProperties connectionProperties = new SshConnectionProperties();
    connectionProperties.setProxyHost(PROX_HOST);
    connectionProperties.setProxyPort(22);
    connectionProperties.setProxyUsername(PROXY_UNAME);
    connectionProperties.setProxyPassword(PROXY_PWD);
    client.connect(connectionProperties, new IgnoreHostKeyVerification());
    //this is behind the firewall and proxy has got access to it
    connectionProperties.setHost(HOST_NAME);
    PasswordAuthenticationClient authenticationClient = new PasswordAuthenticationClient();
    authenticationClient.setUsername(HOST_UNAME);
    authenticationClient.setPassword(HOST_PWD);
    int result = client.authenticate(authenticationClient);
    if (result == AuthenticationProtocolState.COMPLETE)
    System.out.println(“success Authentication”);
    else
    System.out.println(“failed Authentication”);
    System.out.println(client.isConnected());
    SftpClient sftpClient = client.openSftpClient();
    sftpClient.cd(“/”);
    }

  3. It seems your proxy server is not accepting connections thought port 22. Try connecting proxy on port 80 and then do the FTP connection on port 22.

    Luck!

  4. When I set proxy settings and just do a
    client.connect() – it is sucessful
    When I set the HOST and PasswordAuthentication it says connection refused. Is there any exact way to find the exact rejection during authentication. The connection refused exception I am getting is printed in the JUnit console.

  5. Also I would like to know if the SSH and FTP server should reside on the same server for JSSH to work or can they be on a different server IP’s.

  6. We are facing Performance related with J2SSH 0.2.9. When we try to download 1GB file using winscp(sftp) its taking just 15-20 seconds. If we do the same using java progrm with this jar its taking 3min. :-( Any configurations to be set to improve the performance?

  7. Proxy configuration for J2SSH SshClient:

    SshClient client = new SshClient();

    SshConnectionProperties connectionProperties = new SshConnectionProperties();
    connectionProperties.setTransportProvider(SshConnectionProperties.USE_HTTP_PROXY); // or USE_STANDARD_SOCKET or USE_SOCKS4_PROXY or USE_SOCKS5_PROXY
    connectionProperties.setProxyHost(PROX_HOST);
    connectionProperties.setProxyPort(8080);
    connectionProperties.setProxyUsername(PROXY_UNAME);
    connectionProperties.setProxyPassword(PROXY_PWD);
    connectionProperties.setHost(HOST_NAME);
    connectionProperties.setPort(22);

    client.connect(connectionProperties, new IgnoreHostKeyVerification());

  8. An anonymous agent server (then called a net substitute) mainly attempts to anonymize entanglement surfing. There are discrete varieties of anonymizers. Only of the more common variations is the open proxy. Because they are typically intricate to street, unbar proxies are principally useful to those seeking online anonymity, from public dissidents to computer criminals. Some users are at bottom interested in anonymity for the sake of added security, hiding their identities from potentially malicious websites for illustration, or on grounds, to smooth constitutional human rights of unrestraint of idiolect, instead of instance. The server receives requests from the anonymizing representative server, and accordingly does not receive news thither the end purchaser’s address. However, the requests are not anonymous to the anonymizing agent server, and so a rank of trust is present between the delegate server and the user. Many of them are funded through a continued advertising link to the user.

    Access control: Some agent servers gadget a logon requirement. In unrestrained b generally organizations, authorized users requirement log on to attain access to the web. The systematizing can thereby course usage to individuals.

    Some anonymizing proxy servers may forward evidence packets with header lines such as HTTP_VIA, HTTP_X_FORWARDED_ALSO IN BEHALF OF, or HTTP_FORWARDED, which may make known the IP talk to of the client. Other anonymizing substitute servers, known as elite or high anonymity proxies, but take in the REMOTE_ADDR header with the IP oration of the agent server, making it appear that the proxy server is the client. A website could unruffled be suspicious of a proxy is being habituated to if the patron sends packets which register a cookie from a whilom take in that did not profit by the high anonymity substitute server. Clearing cookies, and possibly the reserve, would solve this problem.

    get on facebook at school

Deja un comentario

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s