There are many libraries for this. I suggest Ganymed SSH-2 , which is also mentioned on the official OpenSSH website. On the same site you can also find other libraries that can be used for Java.
This is an example of the ls -r executed via SSH using Ganymed SSH-2:
import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; [...] public static ArrayList<String> lsViaSSH(String hostname, String username, String password, String dir) { ArrayList<String> ls = new ArrayList<String>(); try { Connection conn = new Connection(hostname); conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated == false) { return null; } Session sess = conn.openSession(); sess.execCommand("ls -r " + dir); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); while (true) { String line = br.readLine(); if (line == null) break; ls.add(line); } sess.close(); conn.close(); } catch (IOException e) { return null; } if(StringUtils.isEmpty(ls.get(0))) return null; return ls; }
This is not the only function needed to execute the command through SSH, but I hope this can be a good starting point for you.
source share