Host檔案轉換為Charles可識別的DnsSpoofing Xml配置檔案
阿新 • • 發佈:2018-11-22
charles本身帶有DNS Spoofing Settings的功能,在Tools選單裡,使用這個,就不需要在搭配其他Host修改工具使用了,我們專案中,開發時需要頻繁改host,這個功能對我來說十分有用。
但是charles自帶的這個功能,只能匯入charles本身匯出的xml配置,不能直接匯入host檔案,很不方便,我看了下這個xml的格式,自己寫了個工具來轉化格式,可以把host轉化為charles支援的xml格式來匯入。程式碼下面貼出來,並附上下載連結。
執行下面的命令執行即可,後面的hosts/引數,表示需要轉化的host目錄或檔名
java -jar convertFromHostToCharlesDnsSpoofingXml.jar hosts/
程式碼如下,非常簡單,一看就懂。
package com.example.java; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class MyClass { public static void main(String... args) throws IOException { if (args == null || args.length == 0) { System.out.print("error! no argument! Please enter a file or directory path"); return; } File inputFile = new File(args[0]); if (!inputFile.exists()) { System.out.print(args[0] + "is not a file path"); return; } boolean mkdir = new File("charlesHosts").mkdir(); if (inputFile.isDirectory()) { File[] files = inputFile.listFiles(); if (files == null) { System.out.print("empty directory!"); return; } for (File file : files) { convert(file); } } else { convert(inputFile); } } private static void convert(File file) throws IOException { dnsSpoofing dnsSpoofing = new dnsSpoofing(); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); line = line.replaceAll("[\uFEFF-\uFFFF]", ""); if (line.startsWith("#")) continue; if (line.isEmpty()) continue; String[] split = line.split("\\s+"); dnsSpoof dnsSpoof = new dnsSpoof(); dnsSpoof.address = split[0]; if (split.length < 2) { System.out.print(file); } dnsSpoof.name = split[1]; dnsSpoofing.spoofs.dnsSpoof.add(dnsSpoof); } String s = convertToXml(dnsSpoofing, dnsSpoofing.class); FileWriter writer = new FileWriter("charlesHosts/" + file.getName()); writer.write(s); writer.close(); } public static String convertToXml(Object source, Class type) { String result; StringWriter sw = new StringWriter(); sw.append("<?xml version='1.0' encoding='UTF-8'?>" + "\n"); sw.append("<?charles serialisation-version='2.0' ?>" + "\n"); try { JAXBContext context = JAXBContext.newInstance(type); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(source, sw); result = sw.toString(); } catch (JAXBException e) { throw new RuntimeException(e); } return result; } }