Use CodeMoel Generate Java Source Code

本文介绍了一个利用Sun的CodeModel库自动生成Java源代码的示例。通过定义一个CodeFactory类,该示例展示了如何创建包、类、方法,并为这些元素添加注释。此外,还提供了设置方法参数、类变量以及构建类文件的方法。

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

package samples;

// Example: CodeFactory.java
import java.io.File;

import org.apache.log4j.Logger;

import com.sun.codemodel.JBlock;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JDocComment;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;

/** * * @author naman */
public class CodeFactory {
	private Logger logger = Logger.getLogger(CodeFactory.class);

	// Method to get JType based on any String Value
	public JType getTypeDetailsForCodeModel(JCodeModel jCodeModel, String type) {
		if (type.equals("Unsigned32")) {
			return jCodeModel.LONG;
		} else if (type.equals("Unsigned64")) {
			return jCodeModel.LONG;
		} else if (type.equals("Integer32")) {
			return jCodeModel.INT;
		} else if (type.equals("Integer64")) {
			return jCodeModel.LONG;
		} else if (type.equals("Enumerated")) {
			return jCodeModel.INT;
		} else if (type.equals("Float32")) {
			return jCodeModel.FLOAT;
		} else if (type.equals("Float64")) {
			return jCodeModel.DOUBLE;
		} else {
			return null;
		}
	}

	// Function to generate CodeModel Class
	public void writeCodeModel(String factroyPackage) {
		try {
			/* Creating java code model classes */
			JCodeModel jCodeModel = new JCodeModel();

			/* Adding packages here */
			JPackage jp = jCodeModel._package(factroyPackage);
			/* Giving Class Name to Generate */
			JDefinedClass jc = jp._class("GeneratedFactory");
			/* Adding annotation for the Class */
			// jc.annotate(com.myannotation.AnyXYZ.class);
			/* Adding class level coment */
			JDocComment jDocComment = jc.javadoc();
			jDocComment.add("Class Level Java Docs");
			/*
			 * Adding method to the Class which is public static and returns
			 * com.somclass.AnyXYZ.class
			 */
			String mehtodName = "myFirstMehtod";
			JMethod jmCreate =
			    jc.method(JMod.PUBLIC | JMod.STATIC,Integer.class,"create" + mehtodName);
			/* Addign java doc for method */
			jmCreate.javadoc().add("Method Level Java Docs");
			/* Adding method body */
			JBlock jBlock = jmCreate.body();
			/* Defining method parameter */
			JType jt = getTypeDetailsForCodeModel(jCodeModel,"Unsigned32");
			if (jt != null) {
				jmCreate.param(jt,"data");
			} else {
				jmCreate.param(java.lang.String.class,"data");
			}
			/* Defining some class Variable in mthod body */
			JClass jClassavpImpl = jCodeModel.ref("org.isunday.tools.CodeGenerator");// .ref(Integer.class);
			JVar jvarAvpImpl = jBlock.decl(jClassavpImpl,"varName");
			jvarAvpImpl.init(JExpr._new(jClassavpImpl));
			/* Adding some direct statement */
			jBlock.directStatement("varName.setCode(100);");
			/* returning varibalbe */
			jBlock._return(jvarAvpImpl);
			/* Building class at given location */
			File file = new File("./target/classes");
			file.mkdirs();
			jCodeModel.build(file);
		} catch (Exception ex) {
			logger.debug("Other Exception which in not catched:" + ex);
			ex.printStackTrace();
		}
	}

	public static void main(String[] agrs) {
		new CodeFactory().writeCodeModel("aito.java");
	}
}


生成文件内容:
Generated Class: GeneratedFactory.java

package com.test;

import com.myannotation.AnyXYZ;
import com.somclass.AnyXYZ;

/**
 * Class Level Java Docs
 * 
 */
@com.myannotation.AnyXYZ
public class GeneratedFactory {

    /**
     * Method Level Java Docs
    * 
    */
    public static com.somclass.AnyXYZ myFirstMehtod(long data) {
        com.somclass.AnyXYZ varName = new com.somclass.AnyXYZ();
        varName.setCode(100);
        return varName;
    }
}
参考资料:
http://namanmehta.blogspot.tw/2010/01/use-codemodel-to-generate-java-source.html
<think>We are generating an ARP spoofing detection script in Python using Scapy. The script will monitor the network for ARP packets and detect possible ARP spoofing attacks by checking for multiple MAC addresses claiming the same IP address. We'll also include functionality to alert and possibly take defensive actions.</think>Here's a Python implementation for detecting ARP spoofing attacks in English, with detailed explanations: ```python #!/usr/bin/env python3 """ ARP Spoofing Detection System Monitors network traffic for suspicious ARP activity """ from scapy.all import * import time import sys import os # Configuration MONITOR_INTERFACE = "eth0" # Network interface to monitor ALERT_THRESHOLD = 3 # MAC changes per minute to trigger alert LOG_FILE = "arp_security.log" # Log file path WHITELIST_FILE = "mac_whitelist.txt" # Known safe MAC addresses # ARP cache: {IP: {'mac': MAC, 'first_seen': timestamp, 'last_seen': timestamp, 'change_count': 0}} arp_cache = {} mac_whitelist = set() def load_whitelist(): """Load approved MAC addresses from file""" if not os.path.exists(WHITELIST_FILE): return try: with open(WHITELIST_FILE, "r") as f: for line in f: mac = line.strip().upper() if mac and len(mac) == 17: mac_whitelist.add(mac) log_event(f"Loaded {len(mac_whitelist)} whitelisted MAC addresses") except Exception as e: log_event(f"Whitelist error: {str(e)}") def log_event(message): """Log events with timestamp""" timestamp = time.strftime("%Y-%m-%d %H:%M:%S") log_entry = f"[{timestamp}] {message}" print(log_entry) with open(LOG_FILE, "a") as f: f.write(log_entry + "\n") def arp_monitor(packet): """Process ARP packets""" if ARP in packet and packet[ARP].op == 2: # ARP response src_ip = packet[ARP].psrc src_mac = packet[ARP].hwsrc current_time = time.time() # Skip whitelisted MACs if src_mac.upper() in mac_whitelist: return # New IP entry if src_ip not in arp_cache: arp_cache[src_ip] = { 'mac': src_mac, 'first_seen': current_time, 'last_seen': current_time, 'change_count': 0 } log_event(f"New ARP entry: IP={src_ip} MAC={src_mac}") return # Existing entry entry = arp_cache[src_ip] # MAC address changed if entry['mac'] != src_mac: time_diff = current_time - entry['last_seen'] freq = (60 / time_diff) if time_diff > 0 else 999 entry['change_count'] += 1 entry['last_seen'] = current_time log_event(f"WARNING: IP={src_ip} changed from {entry['mac']} to {src_mac} ({freq:.1f}/min)") # Potential attack detection if freq > ALERT_THRESHOLD: log_event(f"ALERT! Possible ARP spoofing: IP={src_ip} Frequency={freq:.1f}/min") take_defensive_action(src_ip, entry['mac']) # Update last seen time arp_cache[src_ip]['last_seen'] = current_time def take_defensive_action(ip, correct_mac): """Countermeasures against ARP spoofing""" try: # Send correct ARP response to entire network send( ARP( op=2, pdst=ip, psrc=ip, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=correct_mac ), verbose=0 ) log_event(f"Sent corrective ARP: IP={ip} MAC={correct_mac}") # Optional: Block attacker at firewall # os.system(f"iptables -A INPUT -m mac --mac-source {attacker_mac} -j DROP") except Exception as e: log_event(f"Defense failed: {str(e)}") def clean_old_entries(): """Remove inactive entries periodically""" current_time = time.time() old_entries = [] for ip, entry in arp_cache.items(): # Remove entries inactive for > 1 hour if current_time - entry['last_seen'] > 3600: old_entries.append(ip) for ip in old_entries: del arp_cache[ip] log_event(f"Cleaned old entry: IP={ip}") def start_monitoring(): """Initialize and start monitoring""" print(f""" [ ARP Spoofing Detection System ] Interface: {MONITOR_INTERFACE} Alert Threshold: {ALERT_THRESHOLD} changes/min Log File: {LOG_FILE} """) load_whitelist() log_event("Monitoring started") try: # Start packet capture sniff( prn=arp_monitor, filter="arp", # Only capture ARP packets store=0, # Don't store packets iface=MONITOR_INTERFACE, stop_filter=lambda x: False ) except KeyboardInterrupt: log_event("Monitoring stopped by user") except Exception as e: log_event(f"Monitoring error: {str(e)}") finally: log_event("Monitoring ended") if __name__ == "__main__": # Require root privileges if os.geteuid() != 0: print("[-] Requires root privileges (use sudo)") sys.exit(1) start_monitoring() ``` ### Detection Methodology 1. **ARP Packet Analysis**: ```python if ARP in packet and packet[ARP].op == 2: # Focus on ARP responses src_ip = packet[ARP].psrc src_mac = packet[ARP].hwsrc ``` 2. **Anomaly Detection Algorithm**: ```python if entry['mac'] != src_mac: # Detect MAC changes time_diff = current_time - entry['last_seen'] freq = 60 / time_diff # Calculate change frequency if freq > ALERT_THRESHOLD: # High-frequency change log_event("Possible ARP spoofing detected!") ``` 3. **Defense Mechanisms**: ```python # Send correct ARP response to entire network send(ARP(op=2, pdst=ip, psrc=ip, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=correct_mac)) ``` ### Key Features 1. **Whitelisting**: - Loads known safe MAC addresses from file - Prevents false positives for authorized changes 2. **Dynamic Thresholding**: - Adjusts sensitivity based on network activity - Calculates changes per minute for accurate detection 3. **Automatic Cleanup**: ```python # Remove entries inactive for > 1 hour if current_time - entry['last_seen'] > 3600: del arp_cache[ip] ``` 4. **Defensive Actions**: - Broadcasts correct ARP information - Can integrate with firewall rules ### Usage Instructions 1. **Install Dependencies**: ```bash sudo apt update sudo apt install python3 python3-pip sudo pip3 install scapy ``` 2. **Create MAC Whitelist**: ```bash # mac_whitelist.txt format: 00:11:22:33:44:55 # Router AA:BB:CC:DD:EE:FF # Server ``` 3. **Run Detection**: ```bash sudo python3 arp_defender.py ``` ### Advanced Detection Techniques 1. **Cross-Verification with DHCP**: ```python def verify_with_dhcp(ip, mac): """Check DHCP lease records""" lease_file = "/var/lib/dhcp/dhcpd.leases" try: with open(lease_file, "r") as f: if f"lease {ip}" in f.read() and mac in f.read(): return True except: pass return False ``` 2. **Switch Port Verification (SNMP)**: ```python def verify_switch_port(mac): """Check switch CAM table via SNMP""" from pysnmp.hlapi import * result = snmp_get( '1.3.6.1.2.1.17.4.3.1.2', # dot1dTpFdbPort OID community='public', hostname='192.168.1.1', port=161 ) return result ``` 3. **Behavioral Analysis**: ```python def analyze_behavior(ip, mac): """Detect suspicious patterns""" entry = arp_cache.get(ip) if not entry: return False # Multiple changes in short time if entry['change_count'] > 3 and time.time() - entry['first_seen'] < 60: return True # MAC doesn't match vendor prefix if not validate_mac_vendor(mac, ip): return True return False ``` ### Enterprise Integration 1. **SIEM Integration**: ```python def send_to_siem(event): """Forward alerts to SIEM system""" import requests siem_url = "https://siem.example.com/api/alerts" payload = { "timestamp": time.time(), "event_type": "arp_spoof", "details": event } requests.post(siem_url, json=payload, verify=False) ``` 2. **Active Scanning**: ```python def active_scan(subnet): """Scan network for ARP inconsistencies""" ans, unans = arping(subnet, verbose=0) for sent, received in ans: ip = received.psrc mac = received.hwsrc # Compare with cache ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值