以下是一个示例 Java 代码,演示如何通过密钥连接到远程虚拟机并执行这些操作:
import com.jcraft.jsch.*;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.InputStream;
import java.util.Scanner;
public class RemoteFileChecker {
public static void main(String[] args) {
String privateKeyPath = "/path/to/your/ssh_key"; // 本地SSH私钥文件路径
String username = "your_username";
String host = "remote_host";
int port = 22; // SSH默认端口
String remoteFilePath = "/path/to/remote/file"; // 远程文件路径
try {
Session session = connectToRemote(privateKeyPath, username, host, port);
String fileContents = readFileContents(session, remoteFilePath);
if (fileContents != null) {
// 计算文件内容的MD5并保存到变量
String md5Value = calculateMD5(fileContents);
System.out.println("MD5 Value: " + md5Value);
} else {
System.out.println("File doesn't exist or is empty.");
}
// 关闭连接
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Session connectToRemote(String privateKeyPath, String username, String host, int port) throws JSchException {
JSch jsch = new JSch();
jsch.addIdentity(privateKeyPath);
Session session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
return session;
}
private static String readFileContents(Session session, String remoteFilePath) throws JSchException, SftpException {
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
try {
InputStream stream = sftpChannel.get(remoteFilePath);
if (stream != null) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : null;
} else {
return null;
}
} catch (SftpException e) {
return null;
} finally {
sftpChannel.disconnect();
}
}
private static String calculateMD5(String input) {
return DigestUtils.md5Hex(input);
}
}
这个示例代码将连接到远程虚拟机,读取指定的文件的内容。如果文件存在且非空,它将计算文件内容的 MD5 哈希值并将其保存在变量中。如果文件不存在或为空,它将返回相应的消息。请替换示例中的文件路径和密钥路径为你自己的值。确保你的 Java 项目中包含了 JSch 和 Apache Commons Codec 的依赖。