Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to determine if server is FTP or SFTP?

Tags:

java

sftp

ftp

I'm making a class in Java that downloads a specific file from a server. I have a method that can download directly from an FTP server and one from an SFTP server.

Without any assumptions being made on the hostname (without checking if it starts with ftp:// or sftp://, as sometimes the server may be local), is there any way to determine if a server is FTP or SFTP, and therefore which method to use?

Ideally, I'd like to determine programmatically, and not just to try the alternative if it fails. Thanks for any help in advance!

EDIT: For anyone interested, my very basic and definitely not perfect solution is somethign like this:

private int determineServerProtocol(String host, String port) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try (Socket socket = new Socket(host, Integer.parseInt(port))) {
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            result = in.readLine();
            out.close();
            in.close();
        } catch (NumberFormatException | IOException e) {
            e.printStackTrace();
        }
        if (result.contains("SSH")) {
            System.out.println("Server is SFTP");
            // do things...
        } else {
            System.out.println("Server is FTP");
            // do things...
        }
    }
like image 232
Spanner0jjm Avatar asked Nov 07 '22 10:11

Spanner0jjm


1 Answers

You can do a telnet. Apache Commons provides a client side of many intenet protocols.

https://commons.apache.org/proper/commons-net/

And then analyze the answer.

As far as I know, all SSH servers answer something with SSH inside.

telnet demo.wftpserver.com 2222
Trying 199.71.215.197...
Connected to demo.wftpserver.com.
Escape character is '^]'.
SSH-2.0-WingFTPServer

Not SSH

telnet  ftp.funet.fi 21
Trying 193.166.3.2...
Connected to ftp.funet.fi.
Escape character is '^]'.
220 FTP Welcome
like image 186
olikaf Avatar answered Nov 14 '22 22:11

olikaf