如果你不想使用 channel.get
方法来复制文件,你可以尝试使用 SSH 连接远程虚拟机后,使用 Java 进行文件复制和计算 MD5 的操作。下面是一个示例代码:
import com.jcraft.jsch.*;
import java.io.*;
import java.security.MessageDigest;
public class SSHFileTransfer {
public static void main(String[] args) {
String host = "your-remote-host";
String user = "your-username";
String password = "your-password";
String remoteFilePath = "path-to-remote-file";
String localFilePath = "path-to-local-file";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
// 下载文件到本地
InputStream in = sftpChannel.get(remoteFilePath);
OutputStream out = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
// 计算 MD5
String md5 = calculateMD5(localFilePath);
System.out.println("MD5: " + md5);
sftpChannel.disconnect();
session.disconnect();
} catch (JSchException | SftpException | IOException e) {
e.printStackTrace();
}
}
public static String calculateMD5(String filePath) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(filePath);
byte[] dataBytes = new byte[1024];
int nread;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
byte[] mdBytes = md.digest();
StringBuilder md5 = new StringBuilder();
for (byte mdByte : mdBytes) {
md5.append(Integer.toString((mdByte & 0xff) + 0x100, 16).substring(1));
}
return md5.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
请替换示例中的 your-remote-host
、your-username
、your-password
、path-to-remote-file
和 path-to-local-file
为实际的值。这个示例会连接到远程虚拟机,下载文件到本地并计算 MD5 值。需要注意的是,这个示例使用用户名和密码进行认证,不推荐在生产环境中使用明文密码。最佳实践是使用密钥认证来提高安全性