当前位置: 首页 > news >正文

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.lryc.cn/news/300508.html

相关文章:

  • JavaScript- let var const区别
  • 指针的经典笔试题
  • 书生浦语大模型实战营-课程笔记(1)
  • 磁盘database数据恢复: ddrescue,dd和Android 设备的数据拷贝
  • SpringMVC-入门
  • 需要学习的知识点清单
  • 杂谈--spconv导出中onnx的扩展阅读
  • 嵌入式培训机构四个月实训课程笔记(完整版)-Linux ARM驱动编程第二天-arm ads下的start.S分析(物联技术666)
  • STL之list容器的介绍与模拟实现+适配器
  • Leetcode With Golang 二叉树 part1
  • tcp 中使用的定时器
  • 黑马Java——IO流
  • re:从0开始的CSS学习之路 11. 盒子垂直布局
  • Kindling-OriginX 如何集成 DeepFlow 的数据增强网络故障的解释力
  • 轻松掌握Jenkins执行远程window的Jmeter接口脚本
  • UI文件原理
  • OS设备管理
  • Matlab绘图经典代码大全:条形图、极坐标图、玫瑰图、填充图、饼状图、三维网格云图、等高线图、透视图、消隐图、投影图、三维曲线图、函数图、彗星图
  • 姿态传感器MPU6050模块之陀螺仪、加速度计、磁力计
  • MySQL 基础知识(一)之数据库和 SQL 概述
  • 挑战杯 wifi指纹室内定位系统
  • Midjourney提示词风格调试测评
  • Codeforces Round 926 (Div. 2)(A~C)
  • Godot 游戏引擎个人评价和2024年规划(无代码)
  • Win11关闭Windows Defender实时保护,暂时关闭和永久关闭方法 | Win10怎么永久关闭Windows Defender实时保护
  • C# CAD2016 宗地生成界址点,界址点编号及排序
  • [ai笔记7] google浏览器ai学习提效定制优化+常用插件推荐
  • 联想thinkpad-E450双系统升级记
  • Mysql运维篇(四) Xtarbackup--备份与恢复练习
  • vue3 封装一个通用echarts组件