Send ssh command from Java code

2019-02-19 19:23发布

问题:

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

回答1:

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.



回答2:

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();


回答3:

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



标签: java ssh