你可以使用 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操作。