有很多库可以做到这一点.我建议
Ganymed SSH-2,这也在
official OpenSSH website中提到.在同一个站点中,您还可以找到可用于Java的其他库.
这是使用Ganymed SSH-2通过SSH执行的ls -r命令的示例:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
[...]
public static ArrayList lsViaSSH(String hostname, String username, String password, String dir) {
ArrayList ls = new ArrayList();
try
{
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
return null;
}
Session sess = conn.openSession();
sess.execCommand("ls -r " + dir);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
ls.add(line);
}
sess.close();
conn.close();
}
catch (IOException e)
{
return null;
}
if(StringUtils.isEmpty(ls.get(0)))
return null;
return ls;
}
这不是通过SSH执行命令所需的唯一功能,但我希望它可能是一个很好的起点.