java实现远程连接执行命令行与上传下载文件

 更新时间:2024年05月13日 09:57:41   作者:日常500  
这篇文章主要介绍了java实现远程连接执行命令行与上传下载文件方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

遇到一个需要通过java代码对远程Linux系统进行远程操作的场景,其中包括远程执行命令、上传文件、下载文件。

一、maven依赖

<dependency>
	<groupId>com.jcraft</groupId>
	<artifactId>jsch</artifactId>
	<version>0.1.53</version>
</dependency>

二、yml配置

desensitization:
  server:
    ip: xxx #IP地址
    user: root #登录用户名
    password: xxx #登录密码
    port: 22 #远程连接端口
    path: /root/test_data/ #对应处理的目录

三、配置类编写

import com.xxx.fileupload.exception.BizException;
import com.xxx.fileupload.exception.CommonUtilEnum;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: ssh远程连接配置类
 * @author ZXS
 * @date 2022/11/8 9:57
 * @version 1.0
 */
@Configuration
public class JSchSessionConfig {
    //指定的服务器地址
    @Value("${desensitization.server.ip}")
    private String ip;
    //用户名
    @Value("${desensitization.server.user}")
    private String user;
    //密码
    @Value("${desensitization.server.password}")
    private String password;
    //服务器端口 默认22
    @Value("${desensitization.server.port}")
    private String port;

    /**
     * @description: 注入一个bean,jsch.Session
     * @param:
     * @return: com.jcraft.jsch.Session
     * @author ZXS
     * @date: 2022/11/8 9:58
     */
    @Bean
    public Session registSession(){
        Session session;
        try {
            JSch jSch = new JSch();
            //设置session相关配置信息
            session = jSch.getSession(user, ip, Integer.valueOf(port));
            session.setPassword(password);
            //设置第一次登陆的时候提示,可选值:(ask | yes | no)
            session.setConfig("StrictHostKeyChecking", "no");
        } catch (JSchException e) {
            throw new BizException(CommonUtilEnum.FILE_DOWNLOAD_FAIL);
        }
        return session;
    }
}

四、组件工具类的编写

import com.xxx.fileupload.exception.BizException;
import com.xxx.fileupload.exception.CommonUtilEnum;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;

/**
 * @description: ssh远程连接工具类
 * @author ZXS
 * @date 2022/9/28 17:11
 * @version 1.0
 */
@Component
@Slf4j
public class SshRemoteComponent {
    private ThreadLocal<Session> connContainer = new ThreadLocal<>();
    @Resource
    private Session session;

    //上传文件到脱敏服务器的指定目录 自行修改
    @Value("${desensitization.server.path}")
    private String path;

    /**
     * @description: 根据端口号创建ssh远程连接
     * @param: port 端口号
     * @return: com.jcraft.jsch.Session
     * @author ZXS
     * @date: 2022/9/28 15:57
     */
    public Session createConnection(){
        try {
            session.connect(30000);
            connContainer.set(session);
        } catch (JSchException e) {
            throw new BizException(CommonUtilEnum.CONN_FAIL);
        }
        return connContainer.get();
    }

    /**
     * @description: 关闭ssh远程连接
     * @param:
     * @return: void
     * @author ZXS
     * @date: 2022/9/28 15:58
     */
    public void closeConnection(){
        Session session=connContainer.get();
        try {
            if(session != null){
                session.disconnect();
            }
        } catch (Exception e) {
            throw new BizException(CommonUtilEnum.CONN_CLOSE_FAIL);
        }finally {
            connContainer.remove();
        }
    }

    /**
     * @description: ssh通过sftp上传文件
     * @param: session,bytes文件字节流,fileName文件名,resultEncoding 返回结果的字符集编码
     * @return: java.lang.String 执行返回结果
     * @author ZXS
     * @date: 2022/9/30 10:02
     */
    public Boolean sshSftpUpload(Session session, byte[] bytes,String fileName) throws Exception{
        //上传文件到指定服务器的指定目录 自行修改
        //String path = "/root/test_data/";
        Channel channel = null;
        OutputStream outstream = null;
        Boolean flag = true;
        try {
            //创建sftp通信通道
            channel = session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            sftp.cd(path);
            //列出服务器指定的文件列表
            /*Vector v = sftp.ls("*");
            for(int i=0;i<v.size();i++){
               System.out.println(v.get(i));
            }*/
            outstream = sftp.put(fileName);
            outstream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            if(outstream != null){
                outstream.flush();
                outstream.close();
            }
            if(session != null){
                closeConnection();
            }
            if(channel != null){
                channel.disconnect();
            }
        }
        return flag;
    }

    /**
     * @description: ssh通过sftp下载文件
     * @param: session,fileName文件名,filePath 文件下载保存路径
     * @return: java.lang.String 执行返回结果
     * @author ZXS
     * @date: 2022/9/30 10:03
     */
    public Boolean sshSftpDownload(Session session, String fileName, String filePath) throws Exception{
        Channel channel = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream;
        Boolean flag = true;
        try {
            //创建sftp通信通道
            channel = session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            sftp.cd(path);
            inputStream = sftp.get(fileName);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            fileOutputStream = new FileOutputStream(filePath+"/"+fileName);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            byte[] buf = new byte[4096];
            int length = bufferedInputStream.read(buf);
            while (-1 != length){
                bufferedOutputStream.write(buf,0,length);
                length = bufferedInputStream.read(buf);
            }
            bufferedInputStream.close();
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            if(inputStream != null){
                inputStream.close();
            }
            if(session != null){
                closeConnection();
            }
            if(channel != null){
                channel.disconnect();
            }
        }
        return flag;
    }

    /**
     * @description: 远程执行单条Linux命令
     * @param: session,command命令字符串
     * @return: java.lang.String
     * @author ZXS
     * @date: 2022/9/28 16:34
     */
    public Boolean execCommand(Session session, String command){
        //默认方式,执行单句命令
        ChannelExec channelExec;
        Boolean flag = true;
        try {
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();

            /** 判断执行结果 **/
            InputStream in = channelExec.getInputStream();
            byte[] tmp = new byte[1024];
            while(true){
                while(in.available() > 0){
                    int i = in.read(tmp,0,1024);
                    if(i < 0) break;
                    log.info("脚本执行过程:"+new String(tmp,0,i));
                }
                //获取执行结果
                if(channelExec.isClosed()){
                    if(in.available() > 0) continue;
                    if(channelExec.getExitStatus() != 0){
                        //脚本非正常结束,退出吗非零
                        flag = false;
                        log.info("脚本执行出错");
                    }
                    break;
                }
                try{
                    Thread.sleep(1000);
                }catch (Exception e){
                    log.info(e.getMessage());
                }
            }
            channelExec.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}

五、使用测试

@SpringBootTest
@Slf4j
public class TestCase {
    @Resource
    private SshRemoteComponent component;
    @Test
    public void test(){
        Session session = component.createConnection();
        component.execCommand(session, "pwd");
        component.closeConnection();
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java中的线程池ThreadPoolExecutor解析

    Java中的线程池ThreadPoolExecutor解析

    这篇文章主要介绍了Java中的线程池ThreadPoolExecutor解析,线程池,thread pool,是一种线程使用模式,线程池维护着多个线程,等待着监督管理者分配可并发执行的任务,需要的朋友可以参考下
    2023-11-11
  • Hadoop源码分析二安装配置过程详解

    Hadoop源码分析二安装配置过程详解

    本篇是Hadoop源码分析系列文章第二篇,主要介绍Hadoop安装配置的详细过程,后续本系列文章会持续更新,有需要的朋友可以借鉴参考下
    2021-09-09
  • springboot2.0以上调度器配置线程池的实现

    springboot2.0以上调度器配置线程池的实现

    这篇文章主要介绍了springboot2.0以上调度器配置线程池的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • SSH框架网上商城项目第11战之查询和删除商品功能实现

    SSH框架网上商城项目第11战之查询和删除商品功能实现

    这篇文章主要为大家详细介绍了SSH框架网上商城项目第11战之查询和删除商品功能实现的相关资料,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-06-06
  • Servlet和Filter之间的区别与联系

    Servlet和Filter之间的区别与联系

    这篇文章主要介绍了Servlet和Filter之间的区别与联系的相关资料,需要的朋友可以参考下
    2016-05-05
  • JVM 参数配置详细介绍

    JVM 参数配置详细介绍

    这篇文章主要介绍了JVM 参数配置详细介绍的相关资料,需要的朋友可以参考下
    2017-02-02
  • java实现简易外卖订餐系统

    java实现简易外卖订餐系统

    这篇文章主要为大家详细介绍了java实现简易外卖订餐系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • maven如何打包动态环境变量(包括启动脚本)

    maven如何打包动态环境变量(包括启动脚本)

    这篇文章主要介绍了maven如何打包动态环境变量(包括启动脚本)问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • Spring Kafka中@KafkaListener注解的参数与使用小结

    Spring Kafka中@KafkaListener注解的参数与使用小结

    @KafkaListener注解为开发者提供了一种声明式的方式来定义消息监听器,本文主要介绍了Spring Kafka中@KafkaListener注解的参数与使用小结,具有一定的参考价值,感兴趣的可以了解一下
    2024-06-06
  • Java 8中Stream API的这些奇技淫巧!你Get了吗?

    Java 8中Stream API的这些奇技淫巧!你Get了吗?

    这篇文章主要介绍了Java 8中Stream API的这些奇技淫巧!你Get了吗?文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08

最新评论