Working with Libraries – os, socket, and requests for Hacking and Automation
Python libraries give us superpowers to interact with systems, networks, and the web. In this post, we'll look at three core libraries that are incredibly useful for hacking and automation: os
, socket
, and requests
.
1. The os
Module
The os
module provides a way of interacting with the operating system. Useful for automating tasks like file manipulation, command execution, and directory navigation.
import os
# Print current working directory
print(os.getcwd())
# List files in a directory
print(os.listdir("."))
# Run a terminal command
os.system("whoami")
# Create a directory
os.mkdir("test_folder")
# Remove a directory
os.rmdir("test_folder")
# Rename a file
os.rename("old.txt", "new.txt")
# Get environment variables
print(os.environ.get("HOME"))
Common Uses:
- Check existence of files
- Run shell commands
- Create directories
- Get environment variables
2. The socket
Module
socket
is used to create low-level network connections. It is useful for creating custom servers, scanners, or payloads.
import socket
# Get IP of a website
hostname = 'example.com'
ip = socket.gethostbyname(hostname)
print(f"IP of {hostname} is {ip}")
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())
Useful Projects with socket:
- Build a port scanner
- Develop a basic TCP server/client
- Capture or spoof packets
3. The requests
Module
The requests
library makes HTTP requests easier. It's a must-have for web scraping, CTFs, and web app interaction.
Send a GET request:
import requests
response = requests.get("https://httpbin.org/get")
print(response.text)
Send a POST request:
import requests
payload = {"username": "admin", "password": "123"}
response = requests.post("https://httpbin.org/post", data=payload)
print(response.text)
Custom Headers:
import requests
headers = {"User-Agent": "HackerBot/1.0"}
response = requests.get("https://httpbin.org/headers", headers=headers)
print(response.text)
JSON response:
import requests
data = response.json()
print(data)
Common Tasks:
- Login brute-force scripts
- Form submissions
- API consumption
- Automated data extraction
Conclusion
Mastering these standard libraries can greatly speed up your hacking workflow. These are just a few examples, but their real power lies in how you combine them to build automation, tools, or scripts tailored to your recon, scanning, or exploitation needs.
In the next post, we'll cover Functions and Modules in Python — crucial for writing clean and reusable code in large tools. Stay tuned and keep hacking! 🛠️🐍
Comments
Post a Comment