25 Most Popular Python Scripts For Network Security
25 Most Popular Python Scripts For Network Security
if payload in response.text:
print("Potential XSS vulnerability found")
else:
print("No obvious XSS vulnerability detected")
if __name__ == "__main__":
main()
➢ Explanation
# Example usage
if __name__ == "__main__":
example_text = """
Dear user, we've detected suspicious activity on your account. Please
verify your account immediately by visiting this link: https://bit.ly/fake-url
"""
phishing_detector(example_text)
➢ Explanation
def packet_callback(packet):
try:
# For simplicity, we're only looking at IP layer
if packet.haslayer('IP'):
src_ip = packet['IP'].src
dst_ip = packet['IP'].dst
if __name__ == "__main__":
start_sniffing()
➢ Explanation
def check_domain_breaches(domain):
url = f"https://haveibeenpwned.com/api/v3/breaches?domain={domain}"
headers = {
'hibp-api-key': HIBP_API_KEY,
'User-Agent': 'Credential Leak Monitor Script'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
breaches = response.json()
if breaches:
print(f"Breaches found for domain {domain}:")
for breach in breaches:
print(f"- {breach['Name']}: {breach['Description']}")
else:
print(f"No breaches found for domain {domain}.")
else:
print("Error querying Have I Been Pwned API.")
if __name__ == "__main__":
check_domain_breaches(MONITORED_DOMAIN)
➢ Explanation
API key and domain: the script requires an API key from
HIBP and the domain you wish to monitor for breaches.
Request to HIBP: we make a GET request to the HIBP API's
breach endpoint, passing the domain as a query parameter.
Parsing and reporting: the script parses the JSON response
from the API, listing each breach's name and description. This
information can help in understanding the nature and scope of
each breach.
➢ Limitations and considerations
API key and rate limits: HIBP API keys are subject to rate
limiting and other restrictions. Ensure your usage complies
with HIBP's policies.
Privacy and sensitivity: handling data related to breaches
requires sensitivity and adherence to data protection
regulations (e.g., GDPR, CCPA).
Comprehensive monitoring: this script focuses on domain-
related breaches. Comprehensive monitoring might also
involve checking specific email addresses or other identifiers,
depending on your needs and HIBP's capabilities.
➢ Conclusion
This script is a starting point for monitoring public leaks and breaches for
compromised credentials associated with your domain. Expanding its
capabilities and integrating it into your security operations can help in early
detection of potential exposures, enhancing your organization's
cybersecurity posture.
DDoS simulation tool
Creating a Distributed Denial of Service (DDoS) simulation tool is a
delicate subject, as it involves generating high volumes of network traffic to
test the resilience of networks or applications. It's crucial to stress that such
tools must only be used in ethical, legal, and controlled environments. This
means you should only target systems you own or have explicit permission
to test, and you should always consider the impact of your testing on the
network and the services.
Given these considerations, I'll guide you through creating a basic script
that can generate a significant amount of HTTP requests to a target. This
script is intended for educational purposes to understand the concept of
generating high volumes of traffic and should not be used for any
unauthorized testing.
➢ Prerequisites
if __name__ == "__main__":
print("Starting DDoS Simulation...")
start_attack()
print("DDoS Simulation Completed.")
➢ Explanation
Configuration: the `TARGET_URL`, `THREAD_COUNT`,
and `REQUESTS_PER_THREAD` variables allow you to
configure the target and scale of the simulation.
`send_requests` function: this function sends a configured
number of HTTP GET requests to the target URL, simulating
a single source of traffic.
`start_attack` function: initializes and starts multiple threads
(based on `THREAD_COUNT`) to simulate traffic from
multiple sources. It waits for all threads to complete with
`thread.join()`.
➢ Ethical and legal considerations
if __name__ == "__main__":
# Example usage
domain_to_query = 'example.com'
dns_query(domain_to_query, 'A') # A record lookup
dns_query(domain_to_query, 'MX') # MX record lookup
dns_query(domain_to_query, 'NS') # NS record lookup
➢ Explanation
if __name__ == "__main__":
# Example usage
action = input("Do you want to (E)ncrypt or (D)ecrypt a file? ").upper()
if action not in ['E', 'D']:
print("Invalid option.")
else:
file_path = input("Enter the file path: ")
if not os.path.exists(file_path):
print("File does not exist.")
else:
if action == 'E':
generate_key()
key = load_key()
encrypt_file(file_path, key)
elif action == 'D':
key = load_key()
decrypt_file(file_path, key)
➢ Explanation
Key management: the script generates a Fernet key and saves
it to a file. This key is used for both encryption and
decryption. It's crucial to keep this key secure and private.
Encryption and decryption functions: these functions take a
file name and a key as parameters. The file's content is read,
then encrypted or decrypted, and finally written back to the
same file. This replaces the original content with its encrypted
or decrypted form.
User interaction: the script prompts the user to choose
between encryption and decryption, then asks for the file path.
It includes basic error handling for invalid options and missing
files.
➢ Security Considerations
def hash_file(filepath):
"""
Calculate the MD5 hash of a file.
while True:
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
if os.path.isfile(filepath):
# Calculate the current hash
current_hash = hash_file(filepath)
if filepath in file_hashes:
if file_hashes[filepath] != current_hash:
print(f"File changed: {filename}")
file_hashes[filepath] = current_hash
else:
print(f"New file detected: {filename}")
file_hashes[filepath] = current_hash
time.sleep(interval)
if __name__ == "__main__":
directory_to_monitor = input("Enter the directory path to monitor: ")
monitor_interval = int(input("Enter the monitoring interval in seconds:
"))
monitor_directory(directory_to_monitor, monitor_interval)
➢ Explanation
def load_firewall_rules(filename):
"""
Load firewall rules from a JSON file.
def policy_allow_https_only(rule):
"""
Security policy: Allow only HTTPS traffic.
if __name__ == "__main__":
# Load firewall rules from a file (example: 'firewall_rules.json')
rules = load_firewall_rules('firewall_rules.json')
class ImageAnalyzer:
def __init__(self, image_path):
self.image_path = image_path
def open_image(self):
"""
Open the disk image using pytsk3.
"""
try:
# Open the disk image
self.img = pytsk3.Img_Info(self.image_path)
except IOError as e:
print(f"Failed to open image: {e}")
exit()
file_path = f"{parent_path}{entry.info.name.name}"
try:
f_type = entry.info.meta.type
if f_type == pytsk3.TSK_FS_META_TYPE_DIR:
sub_directory = entry.as_directory()
print(f"Directory: {file_path}")
self.recursive_file_listing(sub_directory,
parent_path=file_path + "/")
elif f_type == pytsk3.TSK_FS_META_TYPE_REG:
size = entry.info.meta.size
print(f"File: {file_path}, Size: {size}")
except AttributeError:
# This can happen with some system files
pass
def analyze(self):
"""
Analyze the disk image.
"""
self.open_image()
filesystem = pytsk3.FS_Info(self.img)
directory = filesystem.open_dir(path="/")
print("Starting analysis...")
self.recursive_file_listing(directory)
if __name__ == "__main__":
image_path = "path_to_your_disk_image.dd"
analyzer = ImageAnalyzer(image_path)
analyzer.analyze()
➢ Explanation
def get_file_signature(filepath):
"""
Reads the first few bytes of a file to determine its signature.
"""
signatures = {
'ffd8ffe0': 'JPEG image',
'89504e47': 'PNG image',
# Add more signatures as needed
}
with open(filepath, 'rb') as file:
header = file.read(4) # Read the first 4 bytes
signature = binascii.hexlify(header).decode('utf-8')
for sig in signatures:
if signature.startswith(sig):
return signatures[sig]
return "Unknown file type"
def isolate_system():
"""
Attempts to isolate the system from the network.
This example is for a Windows-based system. Adjust commands for
other OS.
"""
try:
# Disable network adapters
subprocess.run(["powershell", "-Command", "Get-NetAdapter |
Disable-NetAdapter -Confirm:$false"], check=True)
print("System isolated successfully.")
except subprocess.CalledProcessError as e:
print(f"Failed to isolate system: {e}")
sys.exit(1)
if __name__ == "__main__":
isolate_system()
➢ Evidence collection script
This script collects vital system information and logs for further analysis.
It's designed to gather data quickly and comprehensively without needing
manual intervention.
import os
import subprocess
import datetime
import zipfile
def collect_evidence(output_dir="incident_response_evidence"):
"""
Collects system evidence and stores it in the specified output directory.
"""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-
%S")
evidence_dir = f"{output_dir}_{timestamp}"
os.makedirs(evidence_dir, exist_ok=True)
if __name__ == "__main__":
collect_evidence()
➢ Toolkit CLI wrapper (optional)
An optional CLI wrapper can be implemented to provide a unified interface
for launching the various tools within the toolkit. This could be as simple as
a Python script that uses `argparse` or a third-party library like `click` to
handle command-line arguments and options.
➢ Adding more tools
The incident response toolkit can be expanded by adding more scripts for
different tasks, such as:
def analyze_log(file_path):
"""
Analyzes a log file for suspicious activities based on predefined patterns.
try:
with open(file_path, 'r') as file:
for line in file:
for issue, pattern in compiled_patterns.items():
if pattern.search(line):
issues_found[issue] += 1
print(f"Suspicious activity detected [{issue}]:
{line.strip()}")
# Summary of analysis
print("\nSummary of suspicious activities found:")
for issue, count in issues_found.items():
print(f"{issue}: {count}")
except FileNotFoundError:
print("Log file not found. Please check the file path and try again.")
sys.exit(1)
except Exception as e:
print(f"An error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python log_analyzer.py <path_to_log_file>")
sys.exit(1)
log_file_path = sys.argv[1]
analyze_log(log_file_path)
➢ Explanation
def static_analysis(file_path):
"""Performs static analysis on a PE file."""
pe = pefile.PE(file_path)
print("== Static Analysis Results ==")
print(f"File Name: {Path(file_path).name}")
print(f"Number of Sections: {len(pe.sections)}")
# Add more static analysis as needed
def dynamic_analysis(file_path):
"""Performs dynamic analysis by executing the file."""
print("== Dynamic Analysis ==\nWarning: This will execute the
malware. Ensure this is run in a safe environment.")
# Example: subprocess.run(["sandbox_executable", file_path],
check=True)
# Implement sandbox execution and monitoring
def scan_with_virustotal(file_path):
"""Scans the file with VirusTotal."""
vtotal = Virustotal(API_KEY=VIRUSTOTAL_API_KEY)
with open(file_path, "rb") as file:
try:
response = vtotal.file_scan(file)
analysis_id = response["json_resp"]["data"]["id"]
print(f"VirusTotal Analysis ID: {analysis_id}")
# Fetch and display the report using the analysis ID
except Exception as e:
print(f"Error scanning with VirusTotal: {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python malware_analysis_helper.py
<path_to_malware>")
sys.exit(1)
file_path = sys.argv[1]
static_analysis(file_path)
# Uncomment the next line if you wish to perform dynamic analysis
# dynamic_analysis(file_path)
scan_with_virustotal(file_path)
➢ Explanation
Run the script from the command line, passing the path to the
suspected malware file as an argument.
The dynamic analysis section is deliberately simplistic and
must be adapted for actual use, ideally within a secure
sandbox environment.
The script requires external dependencies and a VirusTotal
API key.
➢ Conclusion
This malware analysis helper script provides a foundation for automating
the initial stages of malware investigation. While effective for basic
analysis, it should be expanded with more sophisticated static and dynamic
analysis techniques for professional use. Always ensure that any dynamic
analysis is performed in a secure, isolated environment to prevent
unintended malware execution on critical systems.
Network scanner
Creating a network scanner in Python allows you to identify active devices
on a network by sending ICMP packets (to ping the devices) or by scanning
specific ports. This tool is invaluable for network administrators, security
professionals, and anyone interested in network management or
cybersecurity.
➢ Prerequisites
def icmp_ping_sweep(subnet):
"""Performs an ICMP ping sweep on the given subnet."""
print(f"Starting ICMP ping sweep on {subnet}")
for ip_end in range(1, 255):
ip = f"{subnet}.{ip_end}"
result = subprocess.run(['ping', '-c', '1', ip],
stdout=subprocess.DEVNULL)
if result.returncode == 0:
print(f"Host {ip} is up")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python network_scanner.py <subnet> <port,port,...>")
sys.exit(1)
subnet = sys.argv[1]
ports = [int(port) for port in sys.argv[2].split(',')]
icmp_ping_sweep(subnet)
port_scan(subnet + ".1", ports) # Example usage: scanning the gateway
➢ Explanation
Run the script from the command line, providing the subnet to
scan and a comma-separated list of ports. Example:
python network_scanner.py 192.168.1 22,80,443
def packet_callback(packet):
"""
Callback function to process each captured packet.
Filters for HTTP requests and prints out packet info.
"""
if not packet.haslayer(HTTPRequest):
# Filter for HTTP requests only
return
def start_sniffing(interface="eth0"):
"""
Starts packet sniffing on a given network interface.
"""
print(f"[*] Starting packet sniffing on {interface}...")
sniff(iface=interface, prn=packet_callback, store=False, filter="tcp")
if __name__ == "__main__":
# Customize the interface based on your network configuration
network_interface = "eth0"
start_sniffing(network_interface)
➢ Explanation
# Final evaluation
if (len(password) >= min_length and contains_upper and contains_lower
and
contains_digit and contains_special and is_not_common):
return True
else:
return False
if __name__ == "__main__":
# Example usage
common_passwords_list = ["password", "123456", "12345678"]
test_password = input("Enter a password to test: ")
if check_password_strength(test_password,
common_passwords=common_passwords_list):
print("Password is strong.")
else:
print("Password is weak.")
➢ Explanation
Regular expressions: the script uses Python's `re` module to
check for the presence of uppercase letters, lowercase letters,
digits, and special characters in the password.
Common passwords check: if a list of common passwords is
provided, the script checks to ensure the tested password is not
in this list.
Criteria evaluation: the password is evaluated against the set
criteria, and the function returns `True` if the password meets
all the strength requirements.
➢ Usage and limitations
Run the script and input a password when prompted. For real-
world applications, the list of common passwords should be
expanded and updated regularly.
The script checks basic criteria for password strength. More
sophisticated checks might include patterns, sequences, or
dictionary words.
The common passwords list is hardcoded for demonstration
purposes. In practice, this should be replaced with a
comprehensive, regularly updated list.
➢ Conclusion
This password strength tester script provides a basic framework for
evaluating password complexity. It can be easily expanded or integrated
into user registration processes, encouraging stronger password creation
practices. As cybersecurity threats evolve, enhancing and updating the
criteria and methods for password strength testing is crucial for maintaining
effective security measures.
Port scanner
A port scanner is an essential tool in network security and system
administration, allowing you to identify open ports on a networked device.
These open ports can reveal running services, which might indicate
vulnerabilities or opportunities for further investigation.
➢ Prerequisites
if __name__ == "__main__":
if len(sys.argv) < 4:
print("Usage: python3 port_scanner.py <target> <start_port>
<end_port>")
sys.exit(1)
target_ip = sys.argv[1]
start_port = int(sys.argv[2])
end_port = int(sys.argv[3])
def check_file_policy(policy):
"""
Checks if a file complies with the must_contain and must_not_contain
policies.
"""
with open(policy['path'], 'r') as file:
contents = file.read()
for must in policy.get('must_contain', []):
if must not in contents:
return False
for must_not in policy.get('must_not_contain', []):
if must_not in contents:
return False
return True
def check_command_policy(policy):
"""
Checks if the output of a command complies with the expected output
defined in the policy.
"""
import subprocess
result = subprocess.run(policy['check_command'], shell=True,
capture_output=True, text=True)
return policy['expected_output'] in result.stdout
def check_compliance():
"""
Runs through all security policies and checks compliance.
"""
for name, policy in SECURITY_POLICIES.items():
if 'path' in policy:
result = check_file_policy(policy)
elif 'check_command' in policy:
result = check_command_policy(policy)
else:
result = False # Unknown policy type
if __name__ == "__main__":
check_compliance()
➢ Explanation
Run the script on the target system. Ensure Python 3 and any
necessary permissions or access rights are in place.
The example script is simplified and focuses on file presence
and simple configuration checks. Real-world applications
might require more complex checks, such as validating
permissions, checksums, or integrating with APIs for
centralized management.
Security policies vary widely; thus, the script must be adapted
to match specific organizational or industry standards.
➢ Conclusion
This security policy compliance checker script provides a foundational
approach to automating the verification of system configurations against
security policies. It demonstrates how Python can be utilized to streamline
the compliance checking process, contributing to maintaining a secure and
consistent system environment. Customization and expansion of the script
will be necessary to cover the full range of specific policies relevant to
different systems or organizational requirements.
SSH brute force attack
I must emphasize that using or developing tools for unauthorized access to
systems is illegal and unethical. The information provided here is for
educational purposes only, to understand how such attacks can be
conducted and to reinforce the importance of strong security practices,
including the use of secure passwords and two-factor authentication to
protect against unauthorized access.
Given the sensitive nature of a "SSH brute force attack" tool, I will instead
guide you on how to create a script for educational purposes that simulates
a login attempt to an SSH server, focusing on how to secure systems against
such attacks.
➢ Prerequisites
if __name__ == "__main__":
if len(sys.argv) != 5:
print("Usage: python ssh_login_simulator.py <hostname> <port>
<username> <password>")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python ssl_tls_scanner.py <hostname>")
sys.exit(1)
target_hostname = sys.argv[1]
ssl_tls_scanner(target_hostname)
➢ Explanation
try:
requests.get(url)
print(f"Found: {url}")
found_subdomains.append(url)
except requests.ConnectionError:
# Subdomain does not exist or is not reachable
pass
return found_subdomains
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python subdomain_finder.py <domain>
<subdomains_file>")
sys.exit(1)
target_domain = sys.argv[1]
subdomains_file_path = sys.argv[2]
found = find_subdomains(target_domain, subdomains_file_path)
if found:
print("\nFound subdomains:")
for subdomain in found:
print(subdomain)
else:
print("No subdomains found.")
➢ Explanation
Run the script from the command line, providing the target
domain and the path to your subdomains wordlist file as
arguments.
The script's effectiveness is heavily dependent on the quality
and comprehensiveness of the subdomain wordlist.
It only checks for the subdomain's existence via HTTP and
does not perform deeper DNS record analysis.
Some web configurations or security measures may block or
mislead this type of scanning, affecting accuracy.
➢ Conclusion
This subdomain finder script provides a basic yet effective approach to
discovering potential subdomains for a given domain, which is an essential
step in comprehensive security assessments. While simple, it highlights the
importance of subdomain enumeration in identifying and securing all parts
of a domain. For more advanced or extensive use, consider integrating more
sophisticated DNS querying capabilities or utilizing third-party APIs that
offer subdomain discovery services. Always ensure ethical use of such
tools, respecting privacy and legal restrictions.
Vulnerability scanner
A vulnerability scanner is a tool designed to automate the process of
identifying known vulnerabilities in systems or applications by referencing
databases such as the Common Vulnerabilities and Exposures (CVE) list.
Such scanners are essential for maintaining security by enabling timely
detection and remediation of vulnerabilities.
➢ Prerequisites
def load_cve_database():
"""
Load the CVE database from a local JSON file.
"""
try:
with open(CVE_DATABASE_PATH, 'r') as file:
return json.load(file)
except FileNotFoundError:
print("CVE database file not found.")
sys.exit(1)
except json.JSONDecodeError:
print("Error decoding the CVE database.")
sys.exit(1)
return vulnerabilities
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python vulnerability_scanner.py <software>
<version>")
sys.exit(1)
target_software = sys.argv[1]
target_version = sys.argv[2]
cve_data = load_cve_database()
found_vulnerabilities = scan_for_vulnerabilities(target_software,
target_version, cve_data)
if found_vulnerabilities:
print(f"Vulnerabilities found for {target_software} {target_version}:")
for cve_id in found_vulnerabilities:
print(cve_id)
else:
print(f"No known vulnerabilities found for {target_software}
{target_version}.")
➢ Explanation
def scrape_security_feed(feed_url):
"""
Scrapes a security RSS feed for the latest news and vulnerabilities.
except requests.RequestException as e:
print(f"Error fetching the RSS feed: {e}")
if __name__ == "__main__":
# Example RSS feed URL
rss_feed_url = "https://www.example.com/securityfeed"
scrape_security_feed(rss_feed_url)
➢ Explanation
Run the script with the RSS feed URL of your choice. The
example provided in the script should be replaced with an
actual security news RSS feed URL.
The script is designed for RSS feeds. Scraping websites with
dynamic content loaded via JavaScript may require tools like
Selenium.
Respect rate limiting and legal considerations when scraping
content to avoid being blocked or violating terms of service.
➢ Conclusion
This web scraper for security feeds script provides a straightforward way to
automate the collection of security news from RSS feeds, helping
cybersecurity professionals stay informed about the latest threats and
vulnerabilities. Expanding this script could involve adding features like
automated email notifications, scraping multiple sources concurrently, or
integrating with databases for tracking and analysis. As always, ethical and
legal considerations should guide the use of web scraping tools.
Wireless network scanner
Creating a wireless network scanner in Python that identifies Wi-Fi
networks and devices, assessing them for vulnerabilities, involves
interacting with the system's wireless interfaces and possibly scanning the
environment for Wi-Fi signals. This task is complex and can vary
significantly across operating systems. For educational purposes, I'll guide
you through a basic approach using Python on Linux systems, leveraging
the `iwlist` command, which is commonly available on Linux distributions.
➢ Prerequisites
def scan_networks(interface):
"""
Scans Wi-Fi networks using the specified wireless interface.
ssids = ssid_re.findall(scan_output)
encryption_keys = encryption_re.findall(scan_output)
except subprocess.CalledProcessError:
print(f"Failed to scan networks using interface {interface}. Ensure
you have the necessary permissions.")
sys.exit(1)
except Exception as e:
print(f"An unexpected error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: sudo python3 wireless_network_scanner.py
<interface>")
sys.exit(1)
wlan_interface = sys.argv[1]
scan_networks(wlan_interface)
➢ Explanation
Run the script with root privileges and the wireless interface
name as an argument. Example: `sudo python3
wireless_network_scanner.py wlan0`.
The script is tailored for Linux and might not work on other
operating systems without modification.
It provides basic network information. More sophisticated
vulnerability assessment would require deeper analysis and
possibly active testing, which should be done ethically and
with permission.
➢ Conclusion
This wireless network scanner script offers a foundational approach to
identifying nearby Wi-Fi networks and assessing basic security
configurations. Expanding this tool could involve integrating more
advanced scanning capabilities, automating vulnerability detection based on
encryption types, and possibly interfacing with databases of known
vulnerabilities. Always conduct network scanning and analysis responsibly,
within ethical and legal boundaries.