javaAgent-动态启动

从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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值