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),也叫做微电子机械系统、微系统、微机械等,指尺寸在几毫米乃至更小的高科技装置。微机电系统其内部结构一般在微米甚至纳米量级,是一个独立的智能系统。 微…...
Python爬虫实战:研究MechanicalSoup库相关技术
一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...
树莓派超全系列教程文档--(61)树莓派摄像头高级使用方法
树莓派摄像头高级使用方法 配置通过调谐文件来调整相机行为 使用多个摄像头安装 libcam 和 rpicam-apps依赖关系开发包 文章来源: http://raspberry.dns8844.cn/documentation 原文网址 配置 大多数用例自动工作,无需更改相机配置。但是,一…...
线程同步:确保多线程程序的安全与高效!
全文目录: 开篇语前序前言第一部分:线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分:synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分ÿ…...
visual studio 2022更改主题为深色
visual studio 2022更改主题为深色 点击visual studio 上方的 工具-> 选项 在选项窗口中,选择 环境 -> 常规 ,将其中的颜色主题改成深色 点击确定,更改完成...
C++中string流知识详解和示例
一、概览与类体系 C 提供三种基于内存字符串的流,定义在 <sstream> 中: std::istringstream:输入流,从已有字符串中读取并解析。std::ostringstream:输出流,向内部缓冲区写入内容,最终取…...
微信小程序云开发平台MySQL的连接方式
注:微信小程序云开发平台指的是腾讯云开发 先给结论:微信小程序云开发平台的MySQL,无法通过获取数据库连接信息的方式进行连接,连接只能通过云开发的SDK连接,具体要参考官方文档: 为什么? 因为…...
3403. 从盒子中找出字典序最大的字符串 I
3403. 从盒子中找出字典序最大的字符串 I 题目链接:3403. 从盒子中找出字典序最大的字符串 I 代码如下: class Solution { public:string answerString(string word, int numFriends) {if (numFriends 1) {return word;}string res;for (int i 0;i &…...
【JavaWeb】Docker项目部署
引言 之前学习了Linux操作系统的常见命令,在Linux上安装软件,以及如何在Linux上部署一个单体项目,大多数同学都会有相同的感受,那就是麻烦。 核心体现在三点: 命令太多了,记不住 软件安装包名字复杂&…...
2023赣州旅游投资集团
单选题 1.“不登高山,不知天之高也;不临深溪,不知地之厚也。”这句话说明_____。 A、人的意识具有创造性 B、人的认识是独立于实践之外的 C、实践在认识过程中具有决定作用 D、人的一切知识都是从直接经验中获得的 参考答案: C 本题解…...
技术栈RabbitMq的介绍和使用
目录 1. 什么是消息队列?2. 消息队列的优点3. RabbitMQ 消息队列概述4. RabbitMQ 安装5. Exchange 四种类型5.1 direct 精准匹配5.2 fanout 广播5.3 topic 正则匹配 6. RabbitMQ 队列模式6.1 简单队列模式6.2 工作队列模式6.3 发布/订阅模式6.4 路由模式6.5 主题模式…...
