Ssh in java (running commands on another machine)

I was wondering if there was an easy way to do this as part of a java program.

I would like to be able to ssh to another machine and execute commands on that machine.

A simple example would be: runtime.exec ("welcome the world"); will be (on the poppy) so that the text-to-speech engine speaks in a welcoming world.

Is there a way to run java this method on another computer?

Also, assuming this is possible, is there an ssh way to multiple machines at the same time?

thanks

+4
source share
5 answers

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.

+5
source

Take a look at JSch

As for the performance at the same time? In fact, if you are not going to create multiple threads to process the list of remote computers.

+2
source

given that you are on a system where the ssh command is available and ssh keys are installed to avoid entering passwords, the easiest way would be to simply

 runtime.exec("ssh remote_comp 'say hello world'"); 
+1
source

I would advise you to take a look at Apache MINA SSHD , it can be used to record both client and server with Java

0
source

You can run here , select a library and add code to suit your needs.

-1
source

Source: https://habr.com/ru/post/1469312/


All Articles