java7 与agent_Java利用Attach机制与Agent

本文介绍了如何在Tomcat环境中使用Java Agent进行代码注入,实现进程监控。步骤包括启动Tomcat、编写并打包TestAgent,配置manifest文件,然后通过com.sun.tools.attach API加载并监控所有已加载的类。实践过程中还展示了实际的运行效果和输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先启动一个tomcat,jps查看进程。

b4d7ef97b4b7

image.png

2.编写agent并打包。

package agent;

import java.lang.instrument.Instrumentation;

/**

* @author qishaojun

*/

public class TestAgent {

// public static void premain(String agentArgs, Instrumentation inst) {

// System.out.println("premain start ...");

// System.out.println(agentArgs);

// }

public static void agentmain(String args, Instrumentation inst) {

System.out.println("loadagent after main run.args=" + args);

Class>[] classes = inst.getAllLoadedClasses();

for (Class> cls : classes) {

System.out.println(cls.getName());

}

System.out.println("agent run completely");

}

}

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

sjqi.test

agent

1.0-SNAPSHOT

jar

org.apache.maven.plugins

maven-jar-plugin

2.3.1

true

agent.TestAgent

maven 配置是为了确保jar包打出来的MANIFEST.MF是这样的

Manifest-Version: 1.0

Archiver-Version: Plexus Archiver

Created-By: Apache Maven

Built-By: MC

Build-Jdk: 1.8.0_191

Agent-Class: agent.TestAgent

3.编写操纵程序

//maven引入

com.sun

tools

1.8.0

system

C:/Program Files/Java/jdk1.8.0_191/lib/tools.jar

//代码编写

package com.sprucetec.pop;

import com.sun.tools.attach.AgentInitializationException;

import com.sun.tools.attach.AgentLoadException;

import com.sun.tools.attach.AttachNotSupportedException;

import com.sun.tools.attach.VirtualMachine;

import java.io.IOException;

/**

* @author qishaojun

*/

public class TestAgent {

public static void main(String[] args) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {

VirtualMachine vm=VirtualMachine.attach("2192");

vm.loadAgent("D:/pop-space/agent/target/agent-1.0-SNAPSHOT.jar");

}

}

4.运行效果在tomcat的控制台

b4d7ef97b4b7

image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值