
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(); } } }
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月02日 06时05分40秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
如何提升员工体验 助力企业业务增长?这个棘手的问题终于被解决了!
2021-05-07
AcWing 828. 模拟栈
2021-05-07
OpenAI Gym简介及初级实例
2021-05-07
Java面向对象
2021-05-07
JAVA带标签的break和continue
2021-05-07
Java获取线程基本信息的方法
2021-05-07
(C++11/14/17学习笔记):线程启动、结束,创建线程多法、join,detach
2021-05-07
紫书——蛇形填数
2021-05-07
A Guide to Node.js Logging
2021-05-07
webwxbatchgetcontact一个神奇的接口
2021-05-07
【考研英语-基础-简单句】简单句的核心变化_谓语情态
2021-05-07
实现一个简易Vue(三)Compiler
2021-05-07
仿小米商城(上)
2021-05-07
HTML 和 CSS 简单实现注册页面
2021-05-07
(SpringMVC)springMVC.xml 和 web.xml
2021-05-07
jQuery中的动画
2021-05-07
1.2.3 项目、项目集、项目组合以及运营管理之间的关系
2021-05-07
【△重点△】LeetCode - 4. 寻找两个正序数组的中位数——二分查找
2021-05-07
LeetCode - 5. 最长回文子串——字符串、动态规划
2021-05-07
全局锁和表锁 :给表加个字段怎么有这么多阻碍?
2021-05-07