如何在使用Java的远程系统上运行SSH命令?
答
看一看的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();
答
你可以看看这个基于Java的框架来执行远程命令,包括:通过SSH:https://github.com/jkovacic/remote-exec 它依赖于两个开源的SSH库,无论是JSch(即使支持ECDSA身份验证的实现)或Ganymed(这两个库中的一个都足够了)。乍一看,它可能看起来有点复杂,你必须准备大量的SSH相关类(提供服务器和用户详细信息,指定加密细节,提供OpenSSH兼容私钥等,但SSH本身非常复杂太)。另一方面,模块化设计允许简单包含更多的SSH库,轻松实现其他命令的输出处理甚至交互式类等。
答
下面是在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);
}
}
我张贴一些代码,可能帮助:http://stackoverflow.com/questions/2405885/any-good-jsch-examples – 2013-10-26 21:11:57