2

can anybody show moe how to send from java ssh command ( example ssh root@192.168.0.2 "ls" ) ? What class do I need ?

Damir
  • 54,277
  • 94
  • 246
  • 365
  • possible dublicates http://stackoverflow.com/questions/570450/running-commands-over-ssh-with-java and http://stackoverflow.com/questions/995944/ssh-library-for-java –  Jan 18 '11 at 11:33
  • Remote access for root? Generally not recommended. – Qwerky Jan 18 '11 at 12:30
  • you can use JSch library, but dont do directory listing with command "ls", better use sftp from the same library JSch, much easier to browse remote filesystem. – Ruslan Jan 18 '11 at 12:45
  • Does this answer your question? [SSH library for Java](https://stackoverflow.com/questions/995944/ssh-library-for-java) – EdChum Jul 20 '20 at 08:02

3 Answers3

14

Using sshj:

SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("nameOfServer");
ssh.authPublickey("userId");
Session session = ssh.startSession();
Command cmd = session.exec("yourCommand");
System.out.println(cmd.getOutputAsString());
session.close();
ssh.disconnect();
snakile
  • 52,936
  • 62
  • 169
  • 241
6

You can use JSch or any other Java library. Google will help you.

Although, usually I find it more convenient to execute ssh commands from build script. E.g., there's an Ant task for that.

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
3

an other lib we use is http://www.ganymed.ethz.ch/ssh2/

lweller
  • 11,077
  • 3
  • 34
  • 38