一、引入jar包(基于Maven项目)
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
二、Ganymed SSH2 API文档
Ganymed SSH2 API文档
三、连接实例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class ConnectionSSH{
public static void main(String[] args) {
try {
Connection conn = new Connection("127.0.0.1");
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword("root", "123456");
if (isAuthenticated == false) {
throw new IOException("Authentication failed");
}
final Session sess = conn.openSession();
sess.requestPTY("bash");
sess.startShell();
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
OutputStream out = sess.getStdin();
String temp = "";
try{
out.write(temp.getBytes(StandardCharsets.UTF_8));
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
});
Thread thread1 = new Thread(new Runnable(){
@Override
public void run() {
try{
InputStream stdout = new StreamGobbler(sess.getStdout());
byte[] bytes = new byte[1024];
int i;
while((i = stdout.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, i, StandardCharsets.UTF_8));
}
}catch(IOException e){
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable(){
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
while(scanner.hasNext()) {
try{
String cmd = scanner.next() + "\r";
OutputStream out = sess.getStdin();
out.write(cmd.getBytes(StandardCharsets.UTF_8));
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
}
});
thread.start();
thread1.start();
thread2.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}