从Java5开始,Java提供一种叫做Attach API的机制,允许在运行时将代理程序(agent)附加到已经运行的JVM进程。
步骤1:编写agent
public class MyAgent {
public static void agentmain(String agentArgs, Instrumentation inst) {
// 代理逻辑
}
}
步骤2:编写agent
在 Java Agent JAR 文件中指定 Agent-Class 属性。 在你的代理程序 JAR 文件的 MANIFEST.MF 文件中,指定 Agent-Class 属性,这样 JVM 就知道要调用哪个类的 agentmain 方法。
Manifest-Version: 1.0
Agent-Class: com.example.MyAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
步骤3:打包agent
步骤4:使用 Attach API
编写一个程序或脚本,使用 Attach API 附加你的代理程序到目标 JVM 进程
public class AttachAgent {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java AttachAgent <targetPid>");
return;
}
String targetPid = args[0]; // 从命令行参数获取目标 JVM 进程的 PID
String agentPath = "/path/to/your-agent.jar"; // Java Agent JAR 文件的路径
try {
VirtualMachine vm = VirtualMachine.attach(targetPid);
vm.loadAgent(agentPath);
vm.detach();
System.out.println("Agent attached successfully to process ID " + targetPid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
步骤5:通过命令行运行 AttachAgent 程序,并传递进程 ID 作为参数:
java -cp ".:/path/to/tools.jar" AttachAgent 12345