最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java實(shí)現(xiàn)遠(yuǎn)程連接執(zhí)行命令行與上傳下載文件

 更新時(shí)間:2024年05月13日 09:57:41   作者:日常500  
這篇文章主要介紹了java實(shí)現(xiàn)遠(yuǎn)程連接執(zhí)行命令行與上傳下載文件方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

遇到一個(gè)需要通過(guò)java代碼對(duì)遠(yuǎn)程Linux系統(tǒng)進(jìn)行遠(yuǎn)程操作的場(chǎng)景,其中包括遠(yuǎn)程執(zhí)行命令、上傳文件、下載文件。

一、maven依賴(lài)

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

二、yml配置

desensitization:
  server:
    ip: xxx #IP地址
    user: root #登錄用戶(hù)名
    password: xxx #登錄密碼
    port: 22 #遠(yuǎn)程連接端口
    path: /root/test_data/ #對(duì)應(yīng)處理的目錄

三、配置類(lèi)編寫(xiě)

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遠(yuǎn)程連接配置類(lèi)
 * @author ZXS
 * @date 2022/11/8 9:57
 * @version 1.0
 */
@Configuration
public class JSchSessionConfig {
    //指定的服務(wù)器地址
    @Value("${desensitization.server.ip}")
    private String ip;
    //用戶(hù)名
    @Value("${desensitization.server.user}")
    private String user;
    //密碼
    @Value("${desensitization.server.password}")
    private String password;
    //服務(wù)器端口 默認(rèn)22
    @Value("${desensitization.server.port}")
    private String port;

    /**
     * @description: 注入一個(gè)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();
            //設(shè)置session相關(guān)配置信息
            session = jSch.getSession(user, ip, Integer.valueOf(port));
            session.setPassword(password);
            //設(shè)置第一次登陸的時(shí)候提示,可選值:(ask | yes | no)
            session.setConfig("StrictHostKeyChecking", "no");
        } catch (JSchException e) {
            throw new BizException(CommonUtilEnum.FILE_DOWNLOAD_FAIL);
        }
        return session;
    }
}

四、組件工具類(lèi)的編寫(xiě)

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遠(yuǎn)程連接工具類(lèi)
 * @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;

    //上傳文件到脫敏服務(wù)器的指定目錄 自行修改
    @Value("${desensitization.server.path}")
    private String path;

    /**
     * @description: 根據(jù)端口號(hào)創(chuàng)建ssh遠(yuǎn)程連接
     * @param: port 端口號(hào)
     * @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: 關(guān)閉ssh遠(yuǎn)程連接
     * @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通過(guò)sftp上傳文件
     * @param: session,bytes文件字節(jié)流,fileName文件名,resultEncoding 返回結(jié)果的字符集編碼
     * @return: java.lang.String 執(zhí)行返回結(jié)果
     * @author ZXS
     * @date: 2022/9/30 10:02
     */
    public Boolean sshSftpUpload(Session session, byte[] bytes,String fileName) throws Exception{
        //上傳文件到指定服務(wù)器的指定目錄 自行修改
        //String path = "/root/test_data/";
        Channel channel = null;
        OutputStream outstream = null;
        Boolean flag = true;
        try {
            //創(chuàng)建sftp通信通道
            channel = session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //進(jìn)入服務(wù)器指定的文件夾
            sftp.cd(path);
            //列出服務(wù)器指定的文件列表
            /*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通過(guò)sftp下載文件
     * @param: session,fileName文件名,filePath 文件下載保存路徑
     * @return: java.lang.String 執(zhí)行返回結(jié)果
     * @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 {
            //創(chuàng)建sftp通信通道
            channel = session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //進(jìn)入服務(wù)器指定的文件夾
            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: 遠(yuǎn)程執(zhí)行單條Linux命令
     * @param: session,command命令字符串
     * @return: java.lang.String
     * @author ZXS
     * @date: 2022/9/28 16:34
     */
    public Boolean execCommand(Session session, String command){
        //默認(rèn)方式,執(zhí)行單句命令
        ChannelExec channelExec;
        Boolean flag = true;
        try {
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();

            /** 判斷執(zhí)行結(jié)果 **/
            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("腳本執(zhí)行過(guò)程:"+new String(tmp,0,i));
                }
                //獲取執(zhí)行結(jié)果
                if(channelExec.isClosed()){
                    if(in.available() > 0) continue;
                    if(channelExec.getExitStatus() != 0){
                        //腳本非正常結(jié)束,退出嗎非零
                        flag = false;
                        log.info("腳本執(zhí)行出錯(cuò)");
                    }
                    break;
                }
                try{
                    Thread.sleep(1000);
                }catch (Exception e){
                    log.info(e.getMessage());
                }
            }
            channelExec.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}

五、使用測(cè)試

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

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 使用Java操作MySQL實(shí)現(xiàn)數(shù)據(jù)交互的方法

    使用Java操作MySQL實(shí)現(xiàn)數(shù)據(jù)交互的方法

    JDBC是Java中用于操作數(shù)據(jù)庫(kù)的API,可以為多種關(guān)系數(shù)據(jù)庫(kù)提供統(tǒng)一訪問(wèn),它通過(guò)JDK自帶的JDBC API和數(shù)據(jù)庫(kù)驅(qū)動(dòng)包進(jìn)行操作,實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查,本文給大家介紹使用Java操作MySQL實(shí)現(xiàn)數(shù)據(jù)交互的方法,感興趣的朋友跟隨小編一起看看吧
    2025-01-01
  • Java?多個(gè)文件生成zip包、下載zip包的實(shí)現(xiàn)代碼

    Java?多個(gè)文件生成zip包、下載zip包的實(shí)現(xiàn)代碼

    這篇文章主要介紹了Java?多個(gè)文件生成zip包、下載zip包,包括文件上傳,文件下載,多個(gè)文件打成zip包的操作代碼,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2024-01-01
  • JAVA8妙用Optional解決判斷Null為空的問(wèn)題方法

    JAVA8妙用Optional解決判斷Null為空的問(wèn)題方法

    本文主要介紹了JAVA8妙用Optional解決判斷Null為空的問(wèn)題方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • Java中的包(package)是什么和使用方法

    Java中的包(package)是什么和使用方法

    包是Java中一種強(qiáng)大的組織代碼的工具,它們幫助開(kāi)發(fā)者將代碼分組,防止命名沖突,并通過(guò)控制訪問(wèn)級(jí)別來(lái)增強(qiáng)代碼的安全性,這篇文章主要介紹了Java中的包(package)是什么和如何使用它們,需要的朋友可以參考下
    2024-07-07
  • 如何獲取jar包resources文件路徑

    如何獲取jar包resources文件路徑

    java項(xiàng)目發(fā)布到j(luò)ar之后找不到文件路徑,遇到這樣問(wèn)題如何處理呢,下面小編給大家分享獲取jar包resources文件路徑的解決方法,感興趣的朋友一起看看吧
    2023-12-12
  • Java多態(tài)概念、實(shí)現(xiàn)機(jī)制與實(shí)踐應(yīng)用詳解

    Java多態(tài)概念、實(shí)現(xiàn)機(jī)制與實(shí)踐應(yīng)用詳解

    多態(tài)是指同一個(gè)方法在不同對(duì)象上具有不同的行為,通過(guò)多態(tài)程序可以在運(yùn)行時(shí)決定調(diào)用哪個(gè)方法,從而提高代碼的靈活性和可擴(kuò)展性,這篇文章主要介紹了Java多態(tài)概念、實(shí)現(xiàn)機(jī)制與實(shí)踐應(yīng)用的相關(guān)資料,需要的朋友可以參考下
    2026-01-01
  • SpringBoot獲取配置文件的簡(jiǎn)單實(shí)現(xiàn)方法

    SpringBoot獲取配置文件的簡(jiǎn)單實(shí)現(xiàn)方法

    這篇文章主要給大家介紹了關(guān)于SpringBoot如何獲取配置文件的簡(jiǎn)單實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • SpringBoot多Profile配置的實(shí)現(xiàn)示例

    SpringBoot多Profile配置的實(shí)現(xiàn)示例

    在實(shí)際開(kāi)發(fā)中,我們常常需要根據(jù)不同環(huán)境配置不同的參數(shù),多Profile配置機(jī)制可以幫助我們按需加載配置文件,提升項(xiàng)目的可維護(hù)性和靈活性,感興趣的可以了解一下
    2025-08-08
  • 教你在Spring Boot微服務(wù)中集成gRPC通訊的方法

    教你在Spring Boot微服務(wù)中集成gRPC通訊的方法

    這篇文章主要介紹了教你在Spring Boot微服務(wù)中集成gRPC通訊的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-09-09
  • Spring boot中使用Spring-data-jpa方便快捷的訪問(wèn)數(shù)據(jù)庫(kù)(推薦)

    Spring boot中使用Spring-data-jpa方便快捷的訪問(wèn)數(shù)據(jù)庫(kù)(推薦)

    Spring Data JPA 是 Spring 基于 ORM 框架、JPA 規(guī)范的基礎(chǔ)上封裝的一套JPA應(yīng)用框架,可使開(kāi)發(fā)者用極簡(jiǎn)的代碼即可實(shí)現(xiàn)對(duì)數(shù)據(jù)的訪問(wèn)和操作。這篇文章主要介紹了Spring-boot中使用Spring-data-jpa方便快捷的訪問(wèn)數(shù)據(jù)庫(kù),需要的朋友可以參考下
    2018-05-05

最新評(píng)論

陈巴尔虎旗| 原平市| 翼城县| 泸溪县| 潮安县| 虎林市| 新建县| 潼关县| 博兴县| 襄汾县| 沅陵县| 黔东| 湘乡市| 霸州市| 巢湖市| 和田县| 木兰县| 鹤壁市| 芦山县| 曲阳县| 甘南县| 徐州市| 上高县| 固原市| 博野县| 互助| 凉城县| 扎兰屯市| 清远市| 舒城县| 灵石县| 布拖县| 夹江县| 积石山| 新津县| 香港| 瑞金市| 固始县| 许昌市| 奈曼旗| 漾濞|