can anybody show moe how to send from java ssh command ( example ssh root@192.168.0.2 "ls" ) ? What class do I need ?
Asked
Active
Viewed 4.3k times
2
-
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 Answers
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
-
Thanks for the option. Just bear in mind that this library has 5 library dependencies. – Leonid Dashko Dec 11 '19 at 12:06
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