Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。在使用它的过程中非常容易,只需要指定合法的用户名口令,或者授权认证文件,就可以创建到远程Linux主机的连接,在建立起来的会话中调用该Linux主机上的脚本文件,执行相关操作。
官方API文档:
http://www.ganymed.ethz.ch/ssh2/javadoc/ch/ethz/ssh2/package-summary.html
使用方法:将 ganymed-ssh2-build210.jar 加入到项目的lib中
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class Basic {
public static void main(String[] args) {
String hostname = "192.168.10.100";//远程机器IP
String username = "xxj";//登录用户名
String password = "123456";//登录密码
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
///是否登录成功
if (isAuthenticated == false) {
throw new IOException("认真失败!!!");
}
Session sess = conn.openSession();
//执行命令
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
//创建输入流
InputStream stdout = new StreamGobbler(sess.getStdout());
//字符流
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
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);
System.exit(2);
}
}
}