java远程连接Linux执行命令的三种方式
java远程连接Linux执行命令的三种方式
- 1. 使用JDK自带的RunTime类和Process类实现
- 2. ganymed-ssh2 实现
- 3. jsch实现
- 4. 完整代码:
- 执行shell命令
- 下载和上传文件
1. 使用JDK自带的RunTime类和Process类实现
public static void main(String[] args){Process proc = RunTime.getRunTime().exec("cd /home/tom; ls;")// 标准输入流(必须写在 waitFor 之前)String inStr = consumeInputStream(proc.getInputStream());// 标准错误流(必须写在 waitFor 之前)String errStr = consumeInputStream(proc.getErrorStream());int retCode = proc.waitFor();if(retCode == 0){System.out.println("程序正常执行结束");}
}/*** 消费inputstream,并返回*/
public static String consumeInputStream(InputStream is){BufferedReader br = new BufferedReader(new InputStreamReader(is));String s ;StringBuilder sb = new StringBuilder();while((s=br.readLine())!=null){System.out.println(s);sb.append(s);}return sb.toString();
}
2. ganymed-ssh2 实现
pom
<!--ganymed-ssh2包-->
<dependency><groupId>ch.ethz.ganymed</groupId><artifactId>ganymed-ssh2</artifactId><version>build210</version>
</dependency>
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;public static void main(String[] args){String host = "210.38.162.181";int port = 22;String username = "root";String password = "root";// 创建连接Connection conn = new Connection(host, port);// 启动连接conn.connection();// 验证用户密码conn.authenticateWithPassword(username, password);Session session = conn.openSession();session.execCommand("cd /home/winnie; ls;");// 消费所有输入流String inStr = consumeInputStream(session.getStdout());String errStr = consumeInputStream(session.getStderr());session.close;conn.close();
}/*** 消费inputstream,并返回*/
public static String consumeInputStream(InputStream is){BufferedReader br = new BufferedReader(new InputStreamReader(is));String s ;StringBuilder sb = new StringBuilder();while((s=br.readLine())!=null){System.out.println(s);sb.append(s);}return sb.toString();
}
3. jsch实现
pom
<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version>
</dependency>
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;public static void main(String[] args){String host = "210.38.162.181";int port = 22;String username = "root";String password = "root";// 创建JSchJSch jSch = new JSch();// 获取sessionSession session = jSch.getSession(username, host, port);session.setPassword(password);Properties prop = new Properties();prop.put("StrictHostKeyChecking", "no");session.setProperties(prop);// 启动连接session.connect();ChannelExec exec = (ChannelExec)session.openChannel("exec");exec.setCommand("cd /home/winnie; ls;");exec.setInputStream(null);exec.setErrStream(System.err);exec.connect();// 消费所有输入流,必须在exec之后String inStr = consumeInputStream(exec.getInputStream());String errStr = consumeInputStream(exec.getErrStream());exec.disconnect();session.disconnect();
}/*** 消费inputstream,并返回*/
public static String consumeInputStream(InputStream is){BufferedReader br = new BufferedReader(new InputStreamReader(is));String s ;StringBuilder sb = new StringBuilder();while((s=br.readLine())!=null){System.out.println(s);sb.append(s);}return sb.toString();
}
4. 完整代码:
执行shell命令
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version>
</dependency>
<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version>
</dependency>
<dependency><groupId>ch.ethz.ganymed</groupId><artifactId>ganymed-ssh2</artifactId><version>build210</version>
</dependency>
import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Vector;/*** shell脚本调用类** @author Micky*/
public class SshUtil {private static final Logger logger = LoggerFactory.getLogger(SshUtil.class);private Vector<String> stdout;// 会话sessionSession session;//输入IP、端口、用户名和密码,连接远程服务器public SshUtil(final String ipAddress, final String username, final String password, int port) {try {JSch jsch = new JSch();session = jsch.getSession(username, ipAddress, port);session.setPassword(password);session.setConfig("StrictHostKeyChecking", "no");session.connect(100000);} catch (Exception e) {e.printStackTrace();}}public int execute(final String command) {int returnCode = 0;ChannelShell channel = null;PrintWriter printWriter = null;BufferedReader input = null;stdout = new Vector<String>();try {channel = (ChannelShell) session.openChannel("shell");channel.connect();input = new BufferedReader(new InputStreamReader(channel.getInputStream()));printWriter = new PrintWriter(channel.getOutputStream());printWriter.println(command);printWriter.println("exit");printWriter.flush();logger.info("The remote command is: ");String line;while ((line = input.readLine()) != null) {stdout.add(line);System.out.println(line);}} catch (Exception e) {e.printStackTrace();return -1;}finally {IoUtil.close(printWriter);IoUtil.close(input);if (channel != null) {channel.disconnect();}}return returnCode;}// 断开连接public void close(){if (session != null) {session.disconnect();}}// 执行命令获取执行结果public String executeForResult(String command) {execute(command);StringBuilder sb = new StringBuilder();for (String str : stdout) {sb.append(str);}return sb.toString();}public static void main(String[] args) {String cmd = "ls /opt/";SshUtil execute = new SshUtil("XXX","abc","XXX",22);// 执行命令String result = execute.executeForResult(cmd);System.out.println(result);execute.close();}
}
下载和上传文件
/*** 下载和上传文件*/
public class ScpClientUtil {private String ip;private int port;private String username;private String password;static private ScpClientUtil instance;static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String passward) {if (instance == null) {instance = new ScpClientUtil(ip, port, username, passward);}return instance;}public ScpClientUtil(String ip, int port, String username, String passward) {this.ip = ip;this.port = port;this.username = username;this.password = passward;}public void getFile(String remoteFile, String localTargetDirectory) {Connection conn = new Connection(ip, port);try {conn.connect();boolean isAuthenticated = conn.authenticateWithPassword(username, password);if (!isAuthenticated) {System.err.println("authentication failed");}SCPClient client = new SCPClient(conn);client.get(remoteFile, localTargetDirectory);} catch (IOException ex) {ex.printStackTrace();}finally{conn.close();}}public void putFile(String localFile, String remoteTargetDirectory) {putFile(localFile, null, remoteTargetDirectory);}public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {putFile(localFile, remoteFileName, remoteTargetDirectory,null);}public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {Connection conn = new Connection(ip, port);try {conn.connect();boolean isAuthenticated = conn.authenticateWithPassword(username, password);if (!isAuthenticated) {System.err.println("authentication failed");}SCPClient client = new SCPClient(conn);if ((mode == null) || (mode.length() == 0)) {mode = "0600";}if (remoteFileName == null) {client.put(localFile, remoteTargetDirectory);} else {client.put(localFile, remoteFileName, remoteTargetDirectory, mode);}} catch (IOException ex) {ex.printStackTrace();}finally{conn.close();}}public static void main(String[] args) {ScpClientUtil scpClient = ScpClientUtil.getInstance("XXX", 22, "XXX", "XXX");// 从远程服务器/opt下的index.html下载到本地项目根路径下scpClient.getFile("/opt/index.html","./");// 把本地项目下根路径下的index.html上传到远程服务器/opt目录下scpClient.putFile("./index.html","/opt");}
}
相关文章:
java远程连接Linux执行命令的三种方式
java远程连接Linux执行命令的三种方式 1. 使用JDK自带的RunTime类和Process类实现2. ganymed-ssh2 实现3. jsch实现4. 完整代码:执行shell命令下载和上传文件 1. 使用JDK自带的RunTime类和Process类实现 public static void main(String[] args){Process proc Run…...
JavaScript- let var const区别
let 允许你声明⼀个作⽤域被限制在块级中的变量、语句或者表达式 let 绑定不受变量提升的约束,这意味着 let 声明不会被提升到当前 该变量处于从块开始到初始化处理的“暂存死区” function example() {let x 10;if (true) {let x 20;console.log(x); // Outpu…...
指针的经典笔试题
经典的指针试题,让你彻底理解指针 前言 之前对于指针做了一个详解,现在来看一些关于指针的经典面试题。 再次说一下数组名 数组名通常表示的都是首元素的地址,但是有两个意外,1.sizeof(数组名)这里数组名…...
书生浦语大模型实战营-课程笔记(1)
模型应用过程,大致还是了解的。和之前实习做CV项目的时候比起来,多了智能体这个环节。智能体是个啥? 类似上张图,智能体不太清楚。感觉是偏应用而不是模型的东西? 数据集类型很多,有文本/图片/视频。所以…...
磁盘database数据恢复: ddrescue,dd和Android 设备的数据拷贝
ddrescue和dd 区别: GNU ddrescue 不是 dd 的衍生物,也与 dd 没有任何关系 除了两者都可用于将数据从一台设备复制到另一台设备。 关键的区别在于 ddrescue 使用复杂的算法来复制 来自故障驱动器的数据,尽可能少地造成额外的损坏。ddrescue…...
SpringMVC-入门
1.概念 SpringMVC是一种软件架构思想,把软件按照模型(Model)、视图(View)、控制器(Controller)这三层来划分。Model:指的是工程中JavaBean,用来处理数据View:指的是工程中的html、jsp等页面,用来展示给用户数据Control…...
需要学习的知识点清单
div 4 div 3 F :拓扑排序 G : 组合数学 D : 结构体排序 div 2 div 12...
杂谈--spconv导出中onnx的扩展阅读
Onnx 使用 Onnx 介绍 Onnx (Open Neural Network Exchange) 的本质是一种 Protobuf 格式文件,通常看到的 .onnx 文件其实就是通过 Protobuf 序列化储存的文件。onnx-ml.proto 通过 protoc (Protobuf 提供的编译程序) 编译得到 onnx-ml.pb.h 和 onnx-ml.pb.cc 或 on…...
嵌入式培训机构四个月实训课程笔记(完整版)-Linux ARM驱动编程第二天-arm ads下的start.S分析(物联技术666)
链接:https://pan.baidu.com/s/1E4x2TX_9SYhxM9sWfnehMg?pwd1688 提取码:1688 ; ; NAME: 2440INIT.S ; DESC: C start up codes ; Configure memory, ISR ,stacks ; Initialize C-variables ; 完全注释 ; HISTORY: ; 2002.02.25:kwtark: ver 0.…...
STL之list容器的介绍与模拟实现+适配器
STL之list容器的介绍与模拟实现适配器 1. list的介绍2. list容器的使用2.1 list的定义2.2 list iterator的使用2.3 list capacity2.4 list element access2.5 list modifiers2.6 list的迭代器失效 3. list的模拟实现3.1 架构搭建3.2 迭代器3.2.1 正向迭代器3.2.2反向迭代器适配…...
Leetcode With Golang 二叉树 part1
这一部分主要来梳理二叉树题目最简单最基础的部分,包括遍历,一些简单题目。 一、Leecode 144 - 二叉树的前序遍历 https://leetcode.cn/problems/binary-tree-preorder-traversal/description/ 二叉树的遍历是入门。我们需要在程序一开始就创建一个空…...
tcp 中使用的定时器
定时器的使用场景主要有两种。 (1)周期性任务 这是定时器最常用的一种场景,比如 tcp 中的 keepalive 定时器,起到 tcp 连接的两端保活的作用,周期性发送数据包,如果对端回复报文,说明对端还活着…...
黑马Java——IO流
一、IO流的概述 IO流:存储和读取数据的解决方案 IO流和File是息息相关的 1、IO流的分类 1.1、纯文本文件 word、Excel不是纯文本文件 而txt或者md文件是纯文本文件 2、小结 二、IO流的体系结构 三、字节流 1、FileOutputStream(字节输出流ÿ…...
re:从0开始的CSS学习之路 11. 盒子垂直布局
1. 盒子的垂直布局的注意 若两个“相邻”垂直摆放的盒子,上面盒子的下外边距与下面盒子的上外边距会发生重叠,称为外边距合并 若合并后,外边距会选择重叠外边距的较大值 若两个盒子具有父子关系,则两个盒子的上外边距会发生重叠&…...
Kindling-OriginX 如何集成 DeepFlow 的数据增强网络故障的解释力
DeepFlow 是基于 eBPF 的可观测性开源项目,旨在为复杂的云基础设施及云原生应用提供深度可观测性。DeepFlow 基于 eBPF 采集了精细的链路追踪数据和网络、应用性能指标,其在网络路径上的全链路覆盖能力和丰富的 TCP 性能指标能够为专业用户和网络领域专家…...
轻松掌握Jenkins执行远程window的Jmeter接口脚本
Windows环境:10.1.2.78 新建与配置节点 【系统管理】—【管理节点】—【新建节点】输入节点名称,勾选“dumb slave”,点击ok 按如上配置: 说明: Name:定义slave的唯一名称标识,可以是任意字…...
UI文件原理
使用UI文件创建界面很轻松很便捷,他的原理就是每次我们保存UI文件的时候,QtCreator就自动帮我们将UI文件翻译成C的图形界面创建代码。可以通过以下步骤查看代码 到工程编译目录,一般就是工程同级目录下会生成另一个编译目录,会找到…...
OS设备管理
设备管理 操作系统作为系统资源的管理者,其提供的功能有:处理机管理、存储器管理、文件管理、设备管理。其中前三个管理都是在计算机的主机内部管理其相对应的硬件。 I/O设备 I/O即输入/输出。I/O设备即可以将数据输入到计算机,或者可以接收…...
Matlab绘图经典代码大全:条形图、极坐标图、玫瑰图、填充图、饼状图、三维网格云图、等高线图、透视图、消隐图、投影图、三维曲线图、函数图、彗星图
学会 MATLAB 中的绘图命令对初学者来说具有重要意义,主要体现在以下几个方面: 1. 数据可视化。绘图命令是 MATLAB 中最基本也是最重要的功能之一,它可以帮助初学者将数据可视化,更直观地理解数据的分布、变化规律和趋势。通过绘制图表,可以快速了解数据的特征,从而为后续…...
姿态传感器MPU6050模块之陀螺仪、加速度计、磁力计
MEMS技术 微机电系统(MEMS, Micro-Electro-Mechanical System),也叫做微电子机械系统、微系统、微机械等,指尺寸在几毫米乃至更小的高科技装置。微机电系统其内部结构一般在微米甚至纳米量级,是一个独立的智能系统。 微…...
KubeSphere 容器平台高可用:环境搭建与可视化操作指南
Linux_k8s篇 欢迎来到Linux的世界,看笔记好好学多敲多打,每个人都是大神! 题目:KubeSphere 容器平台高可用:环境搭建与可视化操作指南 版本号: 1.0,0 作者: 老王要学习 日期: 2025.06.05 适用环境: Ubuntu22 文档说…...
Debian系统简介
目录 Debian系统介绍 Debian版本介绍 Debian软件源介绍 软件包管理工具dpkg dpkg核心指令详解 安装软件包 卸载软件包 查询软件包状态 验证软件包完整性 手动处理依赖关系 dpkg vs apt Debian系统介绍 Debian 和 Ubuntu 都是基于 Debian内核 的 Linux 发行版ÿ…...
Auto-Coder使用GPT-4o完成:在用TabPFN这个模型构建一个预测未来3天涨跌的分类任务
通过akshare库,获取股票数据,并生成TabPFN这个模型 可以识别、处理的格式,写一个完整的预处理示例,并构建一个预测未来 3 天股价涨跌的分类任务 用TabPFN这个模型构建一个预测未来 3 天股价涨跌的分类任务,进行预测并输…...
大语言模型如何处理长文本?常用文本分割技术详解
为什么需要文本分割? 引言:为什么需要文本分割?一、基础文本分割方法1. 按段落分割(Paragraph Splitting)2. 按句子分割(Sentence Splitting)二、高级文本分割策略3. 重叠分割(Sliding Window)4. 递归分割(Recursive Splitting)三、生产级工具推荐5. 使用LangChain的…...
最新SpringBoot+SpringCloud+Nacos微服务框架分享
文章目录 前言一、服务规划二、架构核心1.cloud的pom2.gateway的异常handler3.gateway的filter4、admin的pom5、admin的登录核心 三、code-helper分享总结 前言 最近有个活蛮赶的,根据Excel列的需求预估的工时直接打骨折,不要问我为什么,主要…...
srs linux
下载编译运行 git clone https:///ossrs/srs.git ./configure --h265on make 编译完成后即可启动SRS # 启动 ./objs/srs -c conf/srs.conf # 查看日志 tail -n 30 -f ./objs/srs.log 开放端口 默认RTMP接收推流端口是1935,SRS管理页面端口是8080,可…...
Qt Http Server模块功能及架构
Qt Http Server 是 Qt 6.0 中引入的一个新模块,它提供了一个轻量级的 HTTP 服务器实现,主要用于构建基于 HTTP 的应用程序和服务。 功能介绍: 主要功能 HTTP服务器功能: 支持 HTTP/1.1 协议 简单的请求/响应处理模型 支持 GET…...
Java求职者面试指南:Spring、Spring Boot、MyBatis框架与计算机基础问题解析
Java求职者面试指南:Spring、Spring Boot、MyBatis框架与计算机基础问题解析 一、第一轮提问(基础概念问题) 1. 请解释Spring框架的核心容器是什么?它在Spring中起到什么作用? Spring框架的核心容器是IoC容器&#…...
Caliper 配置文件解析:fisco-bcos.json
config.yaml 文件 config.yaml 是 Caliper 的主配置文件,通常包含以下内容: test:name: fisco-bcos-test # 测试名称description: Performance test of FISCO-BCOS # 测试描述workers:type: local # 工作进程类型number: 5 # 工作进程数量monitor:type: - docker- pro…...
脑机新手指南(七):OpenBCI_GUI:从环境搭建到数据可视化(上)
一、OpenBCI_GUI 项目概述 (一)项目背景与目标 OpenBCI 是一个开源的脑电信号采集硬件平台,其配套的 OpenBCI_GUI 则是专为该硬件设计的图形化界面工具。对于研究人员、开发者和学生而言,首次接触 OpenBCI 设备时,往…...
