java通过密钥方式登录连接远程虚拟机把对应目录的rar文件复制到本地虚拟机上

你可以使用 Java 中的 JSch 库来通过密钥(SSH密钥对)方式登录到远程虚拟机,并将远程目录中的RAR文件复制到本地虚拟机上。以下是一个示例:

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class RemoteFileCopy {
    public static void main(String[] args) {
        String remoteHost = "your_remote_host";
        String username = "your_username";
        String privateKeyPath = "/path/to/your/private/key"; // 你的私钥文件路径
        String remoteFilePath = "/path/to/remote/rar/file.rar";
        String localFilePath = "/path/to/local/directory/file.rar";

        JSch jsch = new JSch();
        Session session = null;

        try {
            jsch.addIdentity(privateKeyPath); // 加载私钥
            session = jsch.getSession(username, remoteHost);
            session.connect();

            ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            channelSftp.get(remoteFilePath, localFilePath); // 复制远程文件到本地

            channelSftp.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.disconnect();
            }
        }
    }
}

确保将your_remote_host替换为远程主机的IP地址或域名,your_username替换为登录用户名,以及/path/to/your/private/key替换为你的私钥文件的路径。remoteFilePath是远程RAR文件的路径,localFilePath是本地虚拟机上存储RAR文件的路径。

这段代码将使用SSH密钥连接到远程主机,然后使用SFTP通道将RAR文件从远程主机复制到本地虚拟机。请确保你的SSH密钥配置正确,允许SSH连接和SFTP操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值