Java 使用 Ganymed SSH-2 连接 Linux
发布日期:2021-05-07 20:56:35 浏览次数:25 分类:精选文章

本文共 2259 字,大约阅读时间需要 7 分钟。

一、引入jar包(基于Maven项目)

ch.ethz.ganymed
ganymed-ssh2
build210

二、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();            }    }   }
上一篇:算法的时间复杂度和空间复杂度
下一篇:十 一、C语言创建桌面程序:单选按钮、复选框和分组框控件

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月02日 06时05分40秒