← Intel
Oct 5, 2026 · HackerOnStreet

Python for Penetration Testing Best Guide Part (Part

Customize your Scripts for web application architecture security. XSS , Python for Penetration Testing Best Guide Part (Part -2 ) Customize your Scripts for web application architecture security. XSS , Hello hope you are

python penetrationpython penetration testingpythonpenetrationtestingbestpartsubdomainrecordsresultssubdomainsaaaa
Python for Penetration Testing Best Guide Part (Part

Quick overview

FieldDetail
Topicsubdomain
GuidePython for Penetration Testing Best Guide Part (Part
Tagssubdomain, records, file, results, subdomains, import
LengthAbout 1689 words
Practice ruleAuthorized labs only — stay ethical

Customize your Scripts for web application architecture security. XSS ,


Python for Penetration Testing Best Guide Part (Part -2 )

Customize your Scripts for web application architecture security. XSS ,

Hello hope you are having a wonderful day in previous article I have mention about artificial scope in cyber security and with your love I decided to work continuously on it. Today in this i would like share we are going to decide about choosing the path in training the model for cyber security project.

Before you get started with machine learning in addictions before that you must have better but knowledge about neural networking. So you can understand how actually I neural network work.

Python for Penetration Testing Best Guide
Python is getting famous since last 5 year. And became more popular when PHP get out dated. And the people was looking…python.plainenglish.io
Photo by Artturi Jalli on Unsplash

Why should we use machine learning for punctuation testing and Exploiting WEB ?

Transfer square simple your own train model can understand things better than you lying on 3rd party scripts sometime it’s quite hard to handle this. This case I will let you know about some fact.

If you want to get started on the Jupiter Notebook with python . you have to initialized that what is actually your go for what purpose you are want to train that model. My case I am going to use that model for scanning large amount of subdiments and try to find their LSI if you don’t have information knowledgeable explain you in simple way

local file inclusion (LFI ) is a wonderful that allowed hackers to take access of your sensitive data using different colours in your URL. Allow hackers to create back door reverse TCP or many kind of attack.

  • Define the Problem
  • Clearly understand and define the problem you want to solve.
  • Collect Data:
  • Gather relevant data that is representative of the problem.
  • Prepare Data:
  • Tune Hyper parameters:
  1. Adjust the model’s settings for optimal performance.
  2. Deploy the Model:
  3. Integrate the trained model into a production environment.
  4. Monitor and Maintain:
  5. Interpretability and Documentation:
  6. Understand the model’s decisions and document the entire process.
  7. Continuous Learning:

Define the Problem :

define the problem is very important so when you have a basic knowledge of programming in programming language so things can be quite easy for us in my case I know I am trying to find a solution of so i can find Solution for (XSS ) cross Site scripting , Subdomain Takeover , so I will continue with my one.

Collect the record of old CVE.

CVE collection for training model is Very important. I will use HackerOne , or Some other you can use Exploit-db for Exploits.

import requests
from bs4 import BeautifulSoup
from html_sanitizer import Sanitizer
from concurrent.futures import ThreadPoolExecutor



def read_payloads_from_file(file_path):
try:
with open(file_path, 'r') as file:
payloads = file.read().splitlines()
return payloads
except Exception as e:
print(f"Error reading payloads from file: {e}")
return []

def sanitize_html(html_content):
# Sanitize HTML content to remove malicious code
sanitizer = Sanitizer()
return sanitizer.sanitize(html_content)

def find_input_fields(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
input_fields = soup.find_all('input')
return [field.get('name') for field in input_fields if field.get('name')]

def test_xss(url, payload, method='get', headers=None, session=None):
success = False
try:
if not session:
session = requests.Session()

if method.lower() == 'get':
response = session.get(url, headers=headers)
elif method.lower() == 'post':
response = session.get(url, headers=headers)
else:
print(f"Unsupported HTTP method: {method}")
return

if response.status_code == 200:
input_fields = find_input_fields(response.text)

for field in input_fields:
modified_payload = payload.replace('{input}', field)
modified_response = session.get(url, headers=headers, params={'payload': modified_payload})

if modified_payload in modified_response.text:
print(f"XSS vulnerability found at: {url} in input field: {field} with payload: {modified_payload}")
success = True

except requests.RequestException as e:
print(f"RequestException: {e}")

return success

def handle_response(url, response):
print(f"Status for {url}: {response.status_code}")

# Print response headers
print("Response Headers:")
for header, value in response.headers.items():
print(f"{header}: {value}")

# Print sanitized HTML content
sanitized_html = sanitize_html(response.text)
print("Sanitized HTML Content:")
print(sanitized_html)

if __name__ == "__main__":
target_url = input("Enter the target URL (e.g., https://www.xx.com/writeareview/search?): ")
payloads_file_path = "payloads.txt"
xss_payloads = read_payloads_from_file(payloads_file_path)
custom_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

with requests.Session() as session:
with ThreadPoolExecutor() as executor:
for payload in xss_payloads:
success = executor.submit(test_xss, target_url, payload, method='get', headers=custom_headers, session=session)
if not success.result():
print(f"Payload failed for method 'GET' with payload: {payload}")

success = executor.submit(test_xss, target_url, payload, method='post', headers=custom_headers, session=session)
if not success.result():
print(f"Payload failed for method 'POST' with payload: {payload}")

# Show detailed information about the response
response = session.get(target_url, headers=custom_headers)
handle_response(target_url, response)

Subdomains Finder :

import csv
import dns.resolver
import dns


def get_possible_subdomains(domain, output_file="apple.csv"):
subdomains = []
with open("apple.txt") as f:
subdomains = [line.strip() + "." + domain for line in f]

results = []
save_counter = 0

print(f"[+] Resolved subdomains for {domain}:")
for subdomain in subdomains:
try:
# Skip subdomains with empty labels
if subdomain.count('.') > 1:
# Resolve A (IPv4) records
a_records = [str(answer) for answer in dns.resolver.resolve(subdomain, 'A')]

# Resolve AAAA (IPv6) records
aaaa_records = [str(answer) for answer in dns.resolver.resolve(subdomain, 'AAAA')]

results.append({'Subdomain': subdomain, 'A Records': ', '.join(a_records), 'AAAA Records': ', '.join(aaaa_records)})

print(f" {subdomain} resolved to A: {', '.join(a_records)}, AAAA: {', '.join(aaaa_records)}")

save_counter += 1
if save_counter >= 1:
with open(output_file, 'a', newline='') as csvfile:
fieldnames = ['Subdomain', 'A Records', 'AAAA Records']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

# Check if the file is empty, and write header if necessary
if csvfile.tell() == 0:
writer.writeheader()

writer.writerows(results)

results = [] # Reset the results list
save_counter = 0

except dns.name.EmptyLabel:
print(f" {subdomain} has an empty label, skipping.")
except dns.resolver.NoAnswer:
pass
except dns.resolver.NXDOMAIN:
pass
except Exception as e:
print(f" Error resolving {subdomain}: {str(e)}")

if results:
with open(output_file, 'a', newline='') as csvfile:
fieldnames = ['Subdomain', 'A Records', 'AAAA Records']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

# Check if the file is empty, and write header if necessary
if csvfile.tell() == 0:
writer.writeheader()

writer.writerows(results)

print(f"Results saved to {output_file}")

if __name__ == '__main__':
domain = input("Enter a domain name:")
get_possible_subdomains(domain)

Python script utilizes DNS queries to find and save subdomains, along with A and AAAA records, for a specified domain in a CSV file.

#pip install asyncio nest_asyncio
#pip install asyncio
import pandas
import pandas as pd
import matplotlib.pyplot as plt
import csv
import dns.resolver
import asyncio
import nest_asyncio


# Now you can use asyncio.run() inside your notebook

async def resolve_subdomain(subdomain):
try:#pip install asyncio nest_asyncio
#pip install asyncio
import pandas
import pandas as pd
import matplotlib.pyplot as plt
import csv
import dns.resolver
import asyncio
import nest_asyncio
# Resolve A (IPv4) records
a_records = [str(answer) for answer in dns.resolver.resolve(subdomain, 'A')]

# Resolve AAAA (IPv6) records
aaaa_records = [str(answer) for answer in dns.resolver.resolve(subdomain, 'AAAA')]

return {'Subdomain': subdomain, 'A Records': ', '.join(a_records), 'AAAA Records': ', '.join(aaaa_records)}
except dns.resolver.NXDOMAIN:
return None
except Exception as e:
print(f" Error resolving {subdomain}: {str(e)}")
return None

async def resolve_subdomains(domain, subdomains):
tasks = [resolve_subdomain(subdomain) for subdomain in subdomains]
return await asyncio.gather(*tasks)

def save_results(results, output_file):
with open(output_file, 'a', newline='') as csvfile:
fieldnames = ['Subdomain', 'A Records', 'AAAA Records']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

# Check if the file is empty, and write header if necessary
if csvfile.tell() == 0:
writer.writeheader()

writer.writerows(filter(None, results))

async def get_possible_subdomains(domain, output_file="subdomains.csv"):
subdomains = []
with open("Subdomain.txt") as f:
subdomains = [line.strip() + "." + domain for line in f]

chunk_size = 10 # Number of subdomains to resolve concurrently
results = []

print(f"[+] Resolved subdomains for {domain}:")

for i in range(0, len(subdomains), chunk_size):
chunk = subdomains[i:i+chunk_size]
chunk_results = await resolve_subdomains(domain, chunk)
results.extend(chunk_results)

# Save results periodically
if i % (chunk_size * 10) == 0:
save_results(results, output_file)
results = [] # Reset results

# Save any remaining results
save_results(results, output_file)

print(f"Results saved to {output_file}")

if __name__ == '__main__':
domain = input("Enter a domain name:")
asyncio.run(get_possible_subdomains(domain))
nest_asyncio.apply()
import csv
import concurrent.futures
import dns.resolver
import dns


def resolve_subdomain(subdomain):
try:
a_records = [str(answer) for answer in dns.resolver.resolve(subdomain, 'A')]
aaaa_records = [str(answer) for answer in dns.resolver.resolve(subdomain, 'AAAA')]
return {'Subdomain': subdomain, 'A Records': ', '.join(a_records), 'AAAA Records': ', '.join(aaaa_records)}
except dns.name.EmptyLabel:
print(f" {subdomain} has an empty label, skipping.")
except dns.resolver.NoAnswer:
pass
except dns.resolver.NXDOMAIN:
pass
except Exception as e:
print(f" Error resolving {subdomain}: {str(e)}")
return None

def get_possible_subdomains(domain, input_file="apple.txt", output_file="appleee.csv", batch_size=50):
subdomains = []
with open(input_file) as f:
subdomains = [line.strip() + "." + domain for line in f]

results = []

print(f"[+] Resolved subdomains for {domain}:")

with concurrent.futures.ThreadPoolExecutor() as executor:
resolved_batch = list(executor.map(resolve_subdomain, subdomains))

results.extend(filter(None, resolved_batch))

with open(output_file, 'w', newline='') as csvfile:
fieldnames = ['Subdomain', 'A Records', 'AAAA Records']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(results)

print(f"Results saved to {output_file}")

if __name__ == '__main__':
domain = input("Enter a domain name:")
get_possible_subdomains(domain)

Frequently asked questions

What is this guide about subdomain?

Python for Penetration Testing Best Guide Part (Part explains practical, ethical notes on subdomain. Use it as a structured walkthrough — then practice only in authorized labs.

Who is this subdomain article for?

Readers who want clear, street-level guidance on subdomain without hype. Beginners and intermediate practitioners both benefit.

How do I practice subdomain safely?

Stay in scope: systems you own or have written permission to test. Keep notes, verify findings, and never attack live targets without authorization.