解决fidder小黑怪倒出JMeter文件缺失域名、请求头
1、目录结构:
2、代码
'''
coding:utf-8
@Software:PyCharm
@Time:2024/7/10 14:02
@Author:Dr.zxy
'''
import zipfile
import os
import xml.etree.ElementTree as ET
import re
headers_to_extract = ['Host', 'Connection', 'Content-Length', 'apiversion', 'apicode','User-Agent', 'format', 'content-type', 'accept', 'pagecode','x-secure-opt-log', 'appcode', 'Origin', 'Referer','Accept-Language', 'Accept-Encoding', 'Cookie'
]
def extract_saz(saz_file):extract_folder = saz_file.replace('.saz', '_extracted')os.makedirs(extract_folder, exist_ok=True)with zipfile.ZipFile(saz_file, 'r') as zip_ref:zip_ref.extractall(extract_folder)return extract_folder
def convert_to_txt(extract_folder):for root, _, files in os.walk(extract_folder):for file in files:if not file.endswith('.txt'):original_path = os.path.join(root, file)new_path = os.path.join(root, os.path.splitext(file)[0] + '.txt')os.rename(original_path, new_path)
def update_domain_from_comments(xml_file):tree = ET.parse(xml_file)root = tree.getroot()for sampler in root.findall('.//HTTPSamplerProxy'):testplan_comments = sampler.find(".//stringProp[@name='TestPlan.comments']")if testplan_comments is not None:domain_value = testplan_comments.textdomain_prop = sampler.find(".//stringProp[@name='HTTPSampler.domain']")if domain_prop is not None:domain_prop.text = domain_valuetree.write(xml_file, encoding='utf-8', xml_declaration=True)
def update_testname(filename):tree = ET.parse(filename)root = tree.getroot()header_managers = root.findall('.//HeaderManager')for idx, header_manager in enumerate(header_managers):new_testname = f'{idx:03}-HTTP信息头管理器' header_manager.set('testname', new_testname)tree.write(filename, encoding='utf-8', xml_declaration=True)with open(filename, 'r', encoding='utf-8') as file:content = file.read()pattern = r'<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="000-HTTP信息头管理器" enabled="true">.*?</HeaderManager>\s*<hashTree\s*/>'new_content = re.sub(pattern, '', content, flags=re.DOTALL)with open(filename, 'w', encoding='utf-8') as file:file.write(new_content)
def convert_to_jmeter_xml(directory, headers_to_extract):for filename in os.listdir(directory):if filename.endswith("_c.txt"):file_path = os.path.join(directory, filename)numeric_value = filename.split('_')[0].zfill(3)headers = {}with open(file_path, 'r', encoding='utf-8') as file:content = file.read()for header in headers_to_extract:match = re.search(rf'^{header}: (.+)$', content, flags=re.MULTILINE)if match:headers[header] = match.group(1)header_xml = ''for header, value in headers.items():header_xml += f'''<elementProp name="" elementType="Header"><stringProp name="Header.name">{header}</stringProp><stringProp name="Header.value">{value}</stringProp></elementProp>'''jmeter_xml = f'''<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="{numeric_value}-HTTP信息头管理器" enabled="true"><collectionProp name="HeaderManager.headers">{header_xml}</collectionProp></HeaderManager>'''output_filename = f'{numeric_value}_jmeter.xml'output_path = os.path.join(directory, output_filename)with open(output_path, 'w', encoding='utf-8') as output_file:output_file.write(jmeter_xml)
def extract_testnames(filename):testnames = []tree = ET.parse(filename)root = tree.getroot()for header_manager in root.findall('.//HeaderManager'):testname = header_manager.get('testname', '')if '-' in testname:testnames.append(testname.split('-')[0])return testnames
def read_file_content(filename):with open(filename, 'r', encoding='utf-8') as file:content = file.read()return content
def replace_header_manager_content(filename, testname, replacement_content):tree = ET.parse(filename)root = tree.getroot()for header_manager in root.findall('.//HeaderManager'):if header_manager.get('testname', '').startswith(testname):header_manager.clear()header_manager.text = replacement_contenttree.write(filename, encoding='utf-8', xml_declaration=True)def modify_jmx_file(input_file, output_file):try:with open(input_file, 'r', encoding='utf-8') as f:content = f.read()content = content.replace('<HeaderManager>', '')content = content.replace('</HeaderManager>', '')content = content.replace('<', '<')content = content.replace('>', '>')with open(output_file, 'w', encoding='utf-8') as f:f.write(content)except FileNotFoundError:print(f'Error: File {input_file} not found.')
jmx_filename = 'jmx/33n.jmx'
output_file = 'jmx/new_modified.jmx'if __name__ == "__main__":saz_file_path = 'files/333.saz'extract_folder = extract_saz(saz_file_path)convert_to_txt(extract_folder)print(f"step1---fidder转换完成!提取文件存放在:{extract_folder}")update_domain_from_comments(jmx_filename)print(f"step2---url填充完毕")update_testname(jmx_filename)print(f"step3---信息头管理器【序号】添加完成")convert_to_jmeter_xml(extract_folder+"/raw", headers_to_extract)print(f"step4---信息头管理器【新节点·生成】生成完成")testnames = extract_testnames(jmx_filename)for testname in testnames:xml_filename = os.path.join(extract_folder+"/raw/", f'{testname}_jmeter.xml')if os.path.exists(xml_filename):replacement_content = read_file_content(xml_filename)replace_header_manager_content(jmx_filename, testname, replacement_content)else:print(f"Warning: File {xml_filename} not found.")print(f"step5---信息头管理器【新节点·替换】完成")modify_jmx_file(jmx_filename, output_file)print(f"step6---信息头管理器【新节点·替换清洗】完成")
3、注意事项
4、结果