如何使用Java在远程系统上运行SSH命令?

我是这类Java应用程序的新手,正在寻找一些示例代码,介绍如何使用SSH连接到远程服务器,执行命令,并使用Java作为编程语言获取输出。

看看Runtime.exec()Javadoc

Process p = Runtime.getRuntime().exec("ssh myhost"); PrintStream out = new PrintStream(p.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); out.println("ls -l /home/me"); while (in.ready()) { String s = in.readLine(); System.out.println(s); } out.println("exit"); p.waitFor(); 

JSch是SSH2的纯Java实现,可帮助您在远程计算机上运行命令。 你可以在这里找到它, 这里有一些例子。

您可以使用exec.java

下面是在Java中使用SSh的最简单方法。 下载以下链接中的任何文件并解压缩,然后从解压缩的文件中添加jar文件并添加到项目的构建路径http://www.ganymed.ethz.ch/ssh2/并使用以下方法

 public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{ System.out.println("inside the ssh function"); try { Connection conn = new Connection(serverIp); conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password); if (isAuthenticated == false) throw new IOException("Authentication failed."); ch.ethz.ssh2.Session sess = conn.openSession(); sess.execCommand(command); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); System.out.println("the output of the command is"); while (true) { String line = br.readLine(); if (line == null) break; System.out.println(line); } System.out.println("ExitCode: " + sess.getExitStatus()); sess.close(); conn.close(); } catch (IOException e) { e.printStackTrace(System.err); } } 

您可以查看这个基于Java的远程命令执行框架,包括。 通过SSH: https : //github.com/jkovacic/remote-exec它依赖于两个开源SSH库,JSch(对于此实现甚至支持ECDSA身份validation)或Ganymed(这两个库中的一个就足够了)。 乍一看它可能看起来有点复杂,你必须准备大量的SSH相关类(提供服务器和你的用户细节,指定加密细节,提供OpenSSH兼容的私钥等,但SSH本身相当复杂太)。 另一方面,模块化设计允许简单地包含更多SSH库,轻松实现其他命令的输出处理甚至交互式类等。

几年前我用了ganymede … http://www.cleondris.ch/opensource/ssh2/