JAVA实现Linux SSH文件上传,执行命令行

10 篇文章 0 订阅

导入相关依赖

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

代码实现

import com.jcraft.jsch.*;

import java.io.*;
import java.nio.file.Files;

/**
 * @author CQY
 * @version 1.0
 * @date 2024/8/5 16:49
 * SSH文件上传,执行命令行
 **/
public class TestSSHDemo {

    private static final String REMOTE_HOST = "192.168.5.133";
    private static final int REMOTE_PORT = 22;
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    /**
     * 通过 SSH 上传文件到远程服务器。
     *
     * @param remotePath    远程服务器上的目录路径
     * @param localFilePath 本地文件的路径
     */
    public static void uploadFile(String remotePath, String localFilePath) {
        JSch jsch = null;
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
        FileInputStream fileInputStream = null;

        try {
            jsch = new JSch();
            session = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
            session.setPassword(PASSWORD);

            // 设置配置
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            // 连接
            session.connect();

            // 打开 SFTP 通道
            channel = session.openChannel("sftp");
            channel.connect();

            sftpChannel = (ChannelSftp) channel;

            // 上传文件
            File localFile = new File(localFilePath);
            fileInputStream = new FileInputStream(localFile);
            sftpChannel.put(fileInputStream, remotePath + "/" + localFile.getName());
            System.out.println("文件上传成功");

        } catch (IOException | SftpException | JSchException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (sftpChannel != null) {
                sftpChannel.exit();
            }

            if (channel != null) {
                channel.disconnect();
            }

            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     * 通过 SSH 上传文件到远程服务器,监控上传进度
     *
     * @param remotePath    远程服务器上的目录路径
     * @param localFilePath 本地文件的路径
     */
    public static void uploadFileShowUploadProgress(String remotePath, String localFilePath) {
        JSch jsch = null;
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
        FileInputStream fileInputStream = null;

        try {
            jsch = new JSch();
            session = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
            session.setPassword(PASSWORD);

            // 设置配置
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            // 连接
            session.connect();

            // 打开 SFTP 通道
            channel = session.openChannel("sftp");
            channel.connect();

            sftpChannel = (ChannelSftp) channel;

            // 上传文件
            File localFile = new File(localFilePath);
            long fileSize = localFile.length();
            fileInputStream = new FileInputStream(localFile);

            // 显示上传进度条
            showUploadProgress(sftpChannel, localFile, remotePath, fileSize);

            System.out.println("文件上传成功");

        } catch (IOException | SftpException | JSchException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (sftpChannel != null) {
                sftpChannel.exit();
            }

            if (channel != null) {
                channel.disconnect();
            }

            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     * 显示上传进度
     *
     * @param sftpChannel SFTP通道对象
     * @param localFile   本地文件对象
     * @param remotePath  远程文件路径
     * @param fileSize    文件大小(字节)
     * @throws IOException   当读取本地文件或SFTP操作失败时抛出
     * @throws SftpException 当SFTP协议操作出错时抛出
     */
    private static void showUploadProgress(ChannelSftp sftpChannel, File localFile, String remotePath, long fileSize) throws IOException, SftpException {
        int barLength = 50;
        final long[] bytesTransferred = {0};
        long lastBytesTransferred = 0;
        long startTime = System.currentTimeMillis();

        sftpChannel.put(Files.newInputStream(localFile.toPath()), remotePath + "/" + localFile.getName(), new SftpProgressMonitor() {
            @Override
            public void init(int i, String s, String s1, long l) {
            }

            @Override
            public boolean count(long count) {
                bytesTransferred[0] += count;
                double progress = (double) bytesTransferred[0] / fileSize;
                long elapsedTime = System.currentTimeMillis() - startTime;
                // 更新进度条
                updateProgressBar(progress, barLength, elapsedTime);
                return true;
            }

            @Override
            public void end() {
            }

            private void updateProgressBar(double progress, int barLength, long elapsedTime) {
                int pos = (int) (progress * barLength);
                System.out.print("\r");
                System.out.print("[");
                for (int i = 0; i < barLength; i++) {
                    if (i < pos) System.out.print('=');
                    else if (i == pos) System.out.print('>');
                    else System.out.print(' ');
                }
                System.out.print("] " + ((int) (progress * 100)) + "% " + formatTime(elapsedTime));
            }

            private String formatTime(long timeMillis) {
                long minutes = timeMillis / (1000 * 60);
                long seconds = (timeMillis % (1000 * 60)) / 1000;
                return String.format("%02d:%02d", minutes, seconds);
            }
        }, ChannelSftp.OVERWRITE);
    }

    /**
     * 通过 SSH 执行命令。
     *
     * @param command 要执行的命令
     */
    public static void executeCommand(String command) {
        JSch jsch = null;
        Session session = null;
        Channel channel = null;

        try {
            jsch = new JSch();
            session = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
            session.setPassword(PASSWORD);

            // 设置配置
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            // 连接
            session.connect();

            // 打开 EXEC 通道
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            // 重定向输入流
            InputStream in = channel.getInputStream();
            channel.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            // 读取命令输出
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (channel != null) {
                channel.disconnect();
            }

            if (session != null) {
                session.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        // 文件上传示例调用
//        String remotePath = "/root/test";
//        String localFilePath = "D:\\HCIP\\资料\\20230408-09大数据课程文件.tar";
//        uploadFile(remotePath, localFilePath);

        // 通过 SSH 执行命令 示例调用
        String command = "cd /root/test && ls -ltr";
        executeCommand(command);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值