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");}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/684976.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux优化空间完全卸载mysql——centos7.9

文章目录 ⭐前言⭐linux命令使用&#x1f496; 基础命令&#x1f496; 内存优化&#x1f496; 完全删除mysql ⭐结束 ⭐前言 大家好&#xff0c;我是yma16&#xff0c;本文分享 linux优化空间&完全卸载mysql——centos7.9。 linux内存分配 在Linux中&#xff0c;内存分配是…

第7讲 SpringSecurity执行原理概述

SpringSecurity执行原理概述 spring security的简单原理&#xff1a; SpringSecurity有很多很多的拦截器&#xff0c;在执行流程里面主要有两个核心的拦截器 1&#xff0c;登陆验证拦截器AuthenticationProcessingFilter 2&#xff0c;资源管理拦截器AbstractSecurityInterc…

为什么电路要设计得这么复杂?

首先提出这个问题就很不容易啊&#xff0c;我们看两个精彩回答。 From 骄建&#xff1a; 假设我们回到第一个实用放大电路诞生之前&#xff1a; 某天你开始做一个CS单管放大器&#xff0c;电阻负载&#xff0c;可是有一大堆问题&#xff0c;电阻做的不准&#xff0c;温度对器…

AI:129-基于深度学习的极端天气事件预警

🚀点击这里跳转到本专栏,可查阅专栏顶置最新的指南宝典~ 🎉🎊🎉 你的技术旅程将在这里启航! 从基础到实践,深入学习。无论你是初学者还是经验丰富的老手,对于本专栏案例和项目实践都有参考学习意义。 ✨✨✨ 每一个案例都附带有在本地跑过的关键代码,详细讲解供…

HTML5 Canvas与JavaScript携手绘制动态星空背景

目录 一、程序代码 二、代码原理 三、运行效果 一、程序代码 <!DOCTYPE html> <html> <head> <meta charset"UTF-8"> <title>星空背景</title> </head> <body style"overflow-x:hidden;"><canvas …

wayland(xdg_wm_base) client 使用 dmabuf 最简实例

文章目录 前言一、zwp_linux_dmabuf_v1 协议二、wayland client 使用 zwp_linux_dmabuf_v1 协议传递dma-buf代码实例1. wayland_dmabuf.c 代码实例2. xdg-shell-protocol.c 和 xdg-shell-client-protocol.h3. linux-dmabuf-unstable-v1-client-protocol.h 和 linux-dmabuf-unst…

算法学习(五)哈希表

哈希表 1. 概念 哈希函数也叫散列函数&#xff0c;它对不同的输出值得到一个固定长度的消息摘要。 1>散列结果应当具有同一性&#xff08;输出值尽量均匀&#xff09; 2>雪崩效应&#xff08;微小的输入值变化使得输出值发生巨大的变化&#xff09; 通常有以下几种构…

机器学习算法与Python实战 | 常见统计概率分布实现(内含python代码)

本文来源公众号“机器学习算法与Python实战”&#xff0c;仅用于学术分享&#xff0c;侵权删&#xff0c;干货满满。 原文链接&#xff1a;https://mp.weixin.qq.com/s/0Lgmdvey70wXQcP1XQvylQ 在平时的科研中&#xff0c;我们经常使用统计概率的相关知识来帮助我们进行城市研…

第五节 zookeeper集群与分布式锁_2

1.分布式锁概述 1.1 什么是分布式锁 1&#xff09;要介绍分布式锁&#xff0c;首先要提到与分布式锁相对应的是线程锁。 线程锁&#xff1a;主要用来给方法、代码块加锁。当某个方法或代码使用锁&#xff0c;在同一时刻仅有一个线程执行该方法或该代码段。 线程锁只在同一J…

二分、快排、堆排与双指针

二分 int Binary_Search(vector<int> A,int key){int nA.size();int low0,highn-1,mid;while(low<high){mid(lowhigh)/2;if(A[mid]key)return mid;else if(A[mid]>key)highmid-1;elselowmid1; }return -1; }折半插入排序 ——找到第一个 ≥ \ge ≥tem的元素 voi…

代码随想录Day52 | 打家劫舍

代码随想录Day52 | 打家劫舍 198.打家劫舍213.打家劫舍II337.打家劫舍III 198.打家劫舍 文档讲解&#xff1a;代码随想录 视频讲解&#xff1a; 动态规划&#xff0c;偷不偷这个房间呢&#xff1f;| LeetCode&#xff1a;198.打家劫舍 状态 选与不选 dp数组 dp[j] 表示第j个位…

【医学知识图谱 自动补全 关系抽取】生成模型 + 医学知识图谱 = 发现三元组隐藏的关系实体对

生成模型 医学知识图谱 发现三元组新关系实体对 提出背景问题&#xff1a;如何自动发现并生成医疗领域中未被标注的实体关系三元组&#xff1f;CRVAE模型 提出背景 论文&#xff1a;https://dl.acm.org/doi/pdf/10.1145/3219819.3220010 以条件关系变分自编码器&#xff08;…

第7章 Page449 7.8.9智能指针 std::unique_ptr课堂作业,使用智能指针改写foo()函数

源代码&#xff1a; /** \brief 使用std::unique_ptr改写智能指针章节开始的foo()函数** \param* \param* \return**/ #include <iostream> #include <memory>using namespace std;struct O {~O(){cout << "我是被管的对象。我要被释放啦......" …

php基础学习之文件包含

描述 在一个php脚本中&#xff0c;将另一个php文件包含进来&#xff0c;合作实现某种功能 这个描述看起来似乎和C/Java等语言的头文件/包有点类似&#xff0c;但本质是不一样的 打个比方&#xff1a; C/Java的头文件/包更像是一个工具箱&#xff0c;存放各种很完善的工具&#…

Git快速掌握,通俗易懂

Git分布式版本控制工具 介绍 Git是一个开源的分布式版本控制系统&#xff0c;用于敏捷高效地处理任何或小或大的项目。Git是由Linus Torvalds为了帮助管理Linux内核开发而开发的一个开放源码的版本控制软件。Git可以帮助开发者们管理代码的版本&#xff0c;避免代码冲突&#…

C# 异步方法的使用场景

我一直认为C#的异步方法只是一堆华而不实的东西&#xff0c;坑特别多&#xff0c;比起直接自建线程也没有任何优势。 直到有一天&#xff0c;一个需求场景&#xff0c;让我再次想到了C#的异步方法。 需求场景如下&#xff1a;需要写一个程序控制机械臂完成各种动作。每个动作要…

机器学习分类评估四个术语TP,FP,FN,TN

分类评估方法主要功能是用来评估分类算法的好坏&#xff0c;而评估一个分类器算法的好坏又包括许多项指标。了解各种评估方法&#xff0c;在实际应用中选择正确的评估方法是十分重要的。 这里首先介绍几个常见的模型评价术语&#xff0c;现在假设我们的分类目标只有两类&#x…

Dockerfile 常用指令

1、FROM 指定base镜像。 2、Docker history 显示镜像的构建历史&#xff0c;也就是Dockerfile的执行过程。 Missing 表示无法获取IMAGE ID&#xff0c;通常从Docker Hub下载的镜像会有这个问题。 3、调试Dockerfile&#xff0c;使用sudo docker run -it XXXX&#xff0c;XXXX…

英文单词-计算:Calculate与Compute的区别是什么

英文单词-计算:Calculate与Compute的区别是什么 compute 源自法语&#xff1b;calculate 源自拉丁语。在使用上&#xff0c;calculate 使用得更为广泛 calculate侧重人的分析&#xff0c;而compute侧重机器的运算。 calculator是“计算器”&#xff0c;而computer是“计算机”…

【大数据面试题】007 谈一谈 Flink 背压

一步一个脚印&#xff0c;一天一道面试题&#xff08;有些难点的面试题不一定每天都能发&#xff0c;但每天都会写&#xff09; 什么是背压 Backpressure 在流式处理框架中&#xff0c;如果下游的处理速度&#xff0c;比上游的输入数据小&#xff0c;就会导致程序处理慢&…