java实现scp功能本地与远程服务器之间的文件传输

本文介绍了一种通过Web前端图形界面远程编辑服务器配置文件的方法,使用Java SSH连接实现文件的下载与上传,确保了配置修改的安全性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近遇到一个场景,需要利用web前端以图形化界面的方式修改远程服务器的一些配置文件,我的思路是这样的,首先从远程服务器上把文件拷贝下来,然后在本地修改完成之后再上传到服务器的原路径,下面直接上代码:

从服务器到本地:

    public static boolean getConfFile(String userName, String password, String ipAddr, String clusterPath, String localPath) {
        boolean isAuthed = false;
        boolean status = false;
        try {
            status = InetAddress.getByName(ipAddr).isReachable(1500);
            System.out.println(status);
            if (status) {
                Connection conn = new Connection(ipAddr);
                conn.connect();
                isAuthed = conn.authenticateWithPassword(userName, password);
                System.out.println(isAuthed);
                if (isAuthed) {
                    Session session = conn.openSession();
                    SCPClient scpClient = conn.createSCPClient();
                    scpClient.get(clusterPath, localPath);
                    session.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return isAuthed;
    }

从本地上传到服务器:

    public static boolean putBackConfFile(String userName, String password, String ipAddr, String loadFilePath, String clusterPath) {
        boolean isAuthed = false;
        try {
            if (InetAddress.getByName(ipAddr).isReachable(1500)) {
                Connection conn = new Connection(ipAddr);
                conn.connect();
                isAuthed = conn.authenticateWithPassword(userName, password);
                if (isAuthed) {
                    SCPClient scpClient = conn.createSCPClient();
                    scpClient.put(loadFilePath, clusterPath);
                    conn.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return isAuthed;
    }

所用到的一些依赖:

      <dependency>
          <groupId>org.apache.sshd</groupId>
          <artifactId>sshd-scp</artifactId>
          <version>2.1.0</version>
      </dependency>
      <dependency>
          <groupId>ch.ethz.ganymed</groupId>
          <artifactId>ganymed-ssh2</artifactId>
          <version>build210</version>
      </dependency>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值