Possible Duplicate:
SSH library for Java
我正在查看Apache Commons,但找不到SSH的模块。我正在用Java编写一个自动化任务,该任务是使用SSH从Win7登录到Unix计算机,运行命令,捕获写入文本文件中的结果,然后获取文件并关闭连接。如果不是为了运行命令,我可以使用Apache Commons Net来完成所有操作,但是我需要能够随身携带并运行某些程序。
知道哪个API可以满足此要求吗?
谢谢
最佳答案
我强烈建议jSch
这是生产代码的示例。
private List<String> runNexusCommandViaSSH(String sshuser, String sshpass, String sshhost, String command) throws JSchException, IOException {
List<String> results = new ArrayList<String>();
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(sshuser, sshhost, 22);
session.setPassword(sshpass);
session.setConfig(config);
session.setTimeout(10000);
session.connect();
Channel channel = session.openChannel("shell");
channel.setInputStream(null);
channel.setOutputStream(null);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelShell)channel).setPtyType("vt102");
channel.connect();
byte[] tmp=new byte[1024];
out.write((command + ";exit").getBytes());
out.write(("\n").getBytes());
out.flush();
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
//System.out.println("[debug] breaking at i < 0");
break;
}
String buffer = new String(tmp, 0, i);
results.add(buffer);
//System.out.println("[debug]" + buffer);
if(buffer.contains("REMOTE JSH COMMAND FINISHED")){
System.out.println("[debug] breaking at finished");
break;
}
}
if (channel.isClosed()) {
//System.out.println("[debug] breaking at isClosed");
in.close();
break;
}
}
channel.disconnect();
session.disconnect();
return results;
}
关于java - SSH到Unix,运行命令并从Java中获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12754652/