Cybersecurity protects systems, networks, and data from attacks.
Ethical hacking involves legally testing systems for security weaknesses.
Python is widely used in cybersecurity because it is:
- Easy to learn
- Powerful
- Rich in networking libraries
- Excellent for automation
Important Note
Ethical hacking should only be performed:
- On systems you own
- With proper authorization
Unauthorized hacking is illegal.
Python in Cybersecurity
Python is used for:
- Network scanning
- Packet analysis
- Password auditing
- Automation tools
- Security testing
Popular libraries:
- socket
- scapy
- cryptography
- requests
Network Scanning
Network scanning identifies:
- Active devices
- Open ports
- Running services
Using socket
Python provides:
socket
module for network communication.
Simple Port Scanner
import socket
target = "127.0.0.1"
for port in range(1, 101):
sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)
result = sock.connect_ex(
(target, port)
)
if result == 0:
print(f"Port {port} is open")
sock.close()
Scan Specific Port
import socket
host = "google.com"
port = 80
sock = socket.socket()
result = sock.connect_ex(
(host, port)
)
if result == 0:
print("Port open")
else:
print("Port closed")
sock.close()
Banner Grabbing
Used to identify running services.
import socket
sock = socket.socket()
sock.connect(("example.com", 80))
sock.send(b"HEAD / HTTP/1.1\r\n\r\n")
banner = sock.recv(1024)
print(banner.decode())
sock.close()
Packet Sniffing
Packet sniffing captures network packets.
Used for:
- Traffic analysis
- Security monitoring
- Network debugging
Scapy Library
Install:
pip install scapy
Capture Packets
from scapy.all import sniff
def packet_callback(packet):
print(packet.summary())
sniff(count=5, prn=packet_callback)
Filter TCP Packets
from scapy.all import sniff
sniff(
filter="tcp",
count=10,
prn=lambda p: p.summary()
)
View Packet Details
from scapy.all import sniff
packet = sniff(count=1)[0]
packet.show()
Cryptography Basics
Cryptography secures data using encryption.
Main concepts:
- Encryption
- Decryption
- Hashing
Symmetric Encryption
Same key used for:
- Encryption
- Decryption
Install Cryptography Library
pip install cryptography
Generate Encryption Key
from cryptography.fernet import Fernet
key = Fernet.generate_key()
print(key)
Encrypt Data
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
message = b"Python Security"
encrypted = cipher.encrypt(message)
print(encrypted)
Decrypt Data
decrypted = cipher.decrypt(encrypted)
print(decrypted.decode())
Hashing
Hashing converts data into fixed-length output.
Used for:
- Password storage
- Integrity verification
SHA256 Hash Example
import hashlib
text = "password123"
hash_value = hashlib.sha256(
text.encode()
).hexdigest()
print(hash_value)
Password Checker Example
import hashlib
password = input("Enter password: ")
hashed = hashlib.sha256(
password.encode()
).hexdigest()
print("Hash:", hashed)
Automation Tools
Python can automate security-related tasks.
Examples:
- Log monitoring
- File scanning
- Vulnerability checks
File Integrity Checker
import hashlib
def calculate_hash(filename):
sha256 = hashlib.sha256()
with open(filename, "rb") as file:
while chunk := file.read(4096):
sha256.update(chunk)
return sha256.hexdigest()
print(calculate_hash("data.txt"))
Automated Website Status Checker
import requests
websites = [
"https://google.com",
"https://github.com"
]
for site in websites:
try:
response = requests.get(site)
print(
site,
response.status_code
)
except Exception as e:
print(site, "Error")
Simple Keylogger Warning
Keyloggers capture keyboard input and can be illegal or harmful.
They should only be studied in controlled ethical environments.
Network Monitoring Tool
import psutil
network = psutil.net_io_counters()
print("Bytes Sent:", network.bytes_sent)
print("Bytes Received:", network.bytes_recv)
WHOIS Lookup Example
import socket
domain = "example.com"
ip = socket.gethostbyname(domain)
print("IP Address:", ip)
Practical Example
Simple Network Scanner
import socket
target = input("Enter IP: ")
start_port = 1
end_port = 100
for port in range(
start_port,
end_port + 1
):
sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)
sock.settimeout(0.5)
result = sock.connect_ex(
(target, port)
)
if result == 0:
print(f"Port {port} open")
sock.close()
Advantages of Python in Cybersecurity
✅ Easy scripting
✅ Strong networking support
✅ Excellent automation
✅ Large security libraries
✅ Fast development
Best Practices
✅ Always get permission before testing
✅ Use ethical hacking responsibly
✅ Keep tools updated
✅ Secure sensitive data
✅ Avoid illegal activities
Summary
In this chapter you learned:
✅ Network scanning
✅ Packet sniffing
✅ Cryptography basics
✅ Hashing and encryption
✅ Automation tools in cybersecurity






