Automation for a Hacker: How to Speed Up Routine Pentest Tasks with Your Scripts

Tr0jan_Horse

Moderator
Staff member
MODERATOR
ULTIMATE
PREMIUM
MEMBER
Joined
Oct 23, 2024
Messages
304
Reaction score
8,797
Deposit
0$
1750364980808-webp.79793


Pentesting is not just clicking on keys and feeling like a hacker from Hollywood movies. It is serious work, where a lot of time is spent on routine: scanning networks, brute-forcing passwords, analyzing web applications or digging into open data (OSINT). These tasks, although important, sometimes drive you crazy, because they take up hours that could be spent on something more interesting. This is where automation comes to the rescue: scripts and utilities help throw this burden off your shoulders and focus on the main thing - analysis and creativity.

In this article, we will look at how to automate the main tasks of a pentest: from scanning to reporting. There will be examples of Python code, example commands for cool things like Nuclei, Hydra, and Amass, plus a little bit about CI/CD. But I warn you right away: all the scripts and commands here are purely for example, so that you understand the idea. For a real pentest, they need to be seriously modified. And, of course, do not even think about running them without written permission from the system owner - this may be illegal and definitely unethical. Laws like 272-274 of the Criminal Code of the Russian Federation in Russia, the American Computer Fraud and Abuse Act (CFAA) in terms of prohibiting unauthorized access, or European cybersecurity laws such as the NIS Directive and national laws of EU countries, so let's play by the rules.

[h3]Why automation is your best friend?[/h3]Pentesting is when you spend hours checking ports, testing passwords or digging through server configs. If you do everything manually, you can go crazy, especially if the network is huge or the web application is complex. Automation is like a faithful partner who takes on all the boring stuff:
  • Saves time: Scripts and utilities run faster than you with coffee in your hand.
  • Fewer mistakes: Automatic systems do not make mistakes due to carelessness.
  • Scales like a charm: Want to run a thousand IPs or URLs? Easy!
  • Gives you room to think: While the scripts are running, you analyze and figure out how to bypass the protection.
But don't think that automation is a magic "make everything awesome" button. Without manual analysis, you can miss something important, especially if the vulnerability is tricky. Plus, there are ethical rules that are best not to break:
  • Permission is a must have: Do not go beyond the scope of testing. Without written consent (scope of engagement) - not a step.
  • Don't overload your servers: Set up tools to avoid accidentally causing a DDoS.
  • Know the laws: In Russia - Articles 272-274 of the Criminal Code of the Russian Federation, in the US - CFAA, in the EU - cybersecurity laws (NIS Directive) Don't get into trouble.
Example of scope of engagement:
  • Target:
    Code:
    example.com
  • What is possible: Scanning, password guessing (with limits)
  • What is not allowed: DDoS, social engineering
  • Deadlines:
    Code:
    01/06/2025 – 30/06/2025
  • Contact: [email protected]
[h3]Automating Vulnerability Scanning with Python[/h3]Scanning is the first step of reconnaissance: you need to understand where the weak points are. Doing it manually is like looking for a needle in a haystack, especially if there are hundreds of targets. Python is a magic wand here: flexible, with a bunch of libraries, and understandable even for beginners.

[h4]Example: Parallel scanning of web resources[/h4]Here is a demo script that runs URLs, checking headers and content for vulnerabilities. This is just an example, for a real pentest it needs serious improvement.

Code:
import requests
import ssl
import logging
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin

# Настройка логов, чтобы не теряться в куче инфы
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def scan_vulnerability(url):
    """
    Проверяет URL на уязвимости, смотрит заголовки и содержимое.
    """
    try:
        session = requests.Session()
        session.verify = True  # SSL — это важно
        response = session.get(url, timeout=5, headers={'User -Agent': 'Mozilla/5.0'}, proxies={'http': 'http://proxy:8080', 'https': 'http://proxy:8080'})  # Прокси для анонимности
        # Проверяем заголовки на старое ПО
        server = response.headers.get('Server', '')
        x_powered_by = response.headers.get('X-Powered-By', '')
        if 'PHP/7.4' in x_powered_by or 'Apache/2.4.41' in server:
            logging.warning(f"Старенькое ПО на {url}: {server}, {x_powered_by}")

        # Ищем XSS
        if '<script>alert(' in response.text.lower():
            logging.warning(f"Похоже на XSS на {url}")

        logging.info(f"Прогнал {url} - Статус: {response.status_code}")
    except requests.RequestException as e:
        logging.error(f"Ошибка на {url}: {e}")

def run_scanning(urls, max_workers=10):
    """
    Запускает сканирование пачкой URL-ов.
    """
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        executor.map(scan_vulnerability, urls)

if __name__ == "__main__":
    urls_to_scan = ["https://example1.com", "https://example2.com", "https://example3.com"]
    run_scanning(urls_to_scan)

[h4]What's going on here:[/h4]
  • Logs: Everything is recorded to preserve important information for analysis and reporting.
  • Error handling: If the server does not respond or something goes wrong, the script does not crash.
  • Multithreading: Multiple URLs are checked in a single process, saving time.
  • Proxy and SSL: For security and bypassing blocking.

[h4]Tips for setting up:[/h4]
  • Add BeautifulSoup to HTML parsing and you'll find more signatures.
  • Connect to the CVE database API (for example, NVD) to check software versions.
  • Check redirects and WAF to avoid getting banned.
If you want to learn how to automate data collection using Python and work with various libraries for parsing and analysis, the course " Python for Pentester "] will help you , which will provide all the necessary knowledge and skills for working with Python in the field of information security.

[h3]Automation of password cracking with utilities[/h3]Brute-forcing is an important pentesting tool that tests the strength of credentials. Utilities such as Hydra, Patator, or Medusa automate the process, but require caution to avoid overloading the server. All commands are demos and need to be modified for real use. Use tools only with written permission from the system owner to avoid breaking the law.

1. Hydra is one of the most popular and powerful password cracking tools. It supports over 50 different services and protocols, including SSH, FTP, HTTP, RDP, and many others. Hydra allows you to easily and quickly crack passwords using a list or dictionary, and also provides multithreading support to speed up the process.

Example of using Hydra to brute force passwords via SSH:

Code:
hydra -l root -P /path/to/passwords.txt -t 4 ssh://192.168.1.1

What this command does:
  • Code:
    -l
    admin: Specifies the username (or use -L for a list of users).
  • Code:
    -P
    /path/to/passwords.txt: file with passwords to be brute-forced.
  • Code:
    -t
    4: number of threads (parallel attempts).
  • Code:
    -w
    1: 1 second delay between attempts.
  • Code:
    ssh://192.168.1.1
    : target - in this case the IP address of the server via SSH.

Tip:
  • Use proxy servers or VPN to hide your identity.
  • Set up rate limits and timeout settings to avoid being blocked by the target.
  • If you have a list of users , use -L to guess passwords for all users.

2. Medusa is another powerful password cracking utility similar to Hydra, but with an emphasis on simplicity and parallelism. Medusa supports services such as HTTP, FTP, MySQL, SSH, and others. It provides a variety of settings, allowing you to tailor the cracking process to different scenarios.

Example of using Medusa to brute force passwords via FTP:

Code:
medusa -h 192.168.1.1 -u admin -P /path/to/passwords.txt -M ftp

What this command does:
  • Code:
    -h 192.168.1.1
    : IP address of the host.
  • Code:
    -u admin
    : username.
  • Code:
    -P /path/to/passwords.txt
    : path to the file with passwords.
  • Code:
    -M ftp
    : specifies that the search will be performed for FTP.

Tip:
  • Use a proxy: Set up a proxy (-x in Hydra) to anonymize and bypass possible IP blocking.
  • Limit the load: Set the thread count low (-t 2 or 4) and test in small batches to minimize the risk of overloading the server.
  • Check server limits: Before you start brute forcing, make sure you understand the limits of the target system:

Code:
nmap -p 22 192.168.1.1 --script ssh-auth-methods

This will show the available authentication methods and may hint at the presence of protection such as fail2ban.

3. Patator is a universal password cracking utility with support for various services such as HTTP, FTP, SSH, and others. It is more flexible than Hydra and Medusa and offers many useful options for automating attacks.

Example of using Patator to brute force passwords on an HTTP server:

Code:
patator http_fuzz url=https://example.com/login method=POST body="username=admin&password=^PASS^" 0=^passwords.txt

What this command does:
  • Code:
    http_fuzz
    : indicates that an attack will be carried out on the HTTP server.
  • Code:
    url=https://example.com/login
    : address of the target server.
  • Code:
    method=POST
    : method of sending data (POST request).
  • Code:
    body="username=admin&password=^PASS^"
    : data for the authorization form, where ^PASS^ is a variable for substituted passwords.
  • Code:
    0=^passwords.txt
    : list of passwords to guess.

[h4]Creating an effective password dictionary[/h4]
  • The quality of the dictionary determines the success of the search. Targeted dictionaries that take into account the context of the target (names, company terms) are more effective than general lists like RockYou.

1. Crunch creates dictionaries based on given characters or patterns.

Code:
crunch 6 8 0123456789abcdef -o passwords.txt

Explanation: Generates 6-8 character passwords from hexadecimal characters.

When to use: If you know the password format (e.g. PIN or "name + numbers"). For patterns, use -t:

Code:
crunch 6 6 -t @@@@@% -o custom.txt

Where @ are letters, % are numbers (for example, “admin23”).

2. CeWL extracts words from a website to create a dictionary.

Code:
cewl -d 2 -m 5 -w custom_wordlist.txt https://example.com

Explanation: Collects words with a length of 5 characters or more with a crawl depth of 2.

When to use: For passwords related to site content (e.g. "Company2025").

3. Filtering ready-made dictionaries can be optimized using grep:

Code:
grep -E '^.{8,12}$' rockyou.txt > filtered_rockyou.txt

The command searches for all lines in the rockyou.txt file that are between 8 and 12 characters long and saves them in filtered_rockyou.txt.

Add context (eg year):

Code:
awk '{print $0 "2025"}' filtered_rockyou.txt > custom_2025.txt

4. Mutations with John the Ripper creates variations of passwords (for example, "password" → "p@ssw0rd").

Code:
john --wordlist=base_wordlist.txt --rules --stdout > mutated_wordlist.txt

When to use: To take into account user habits (replacing letters with numbers, adding symbols).

Tip:
  • Analyze the target: Use OSINT (e.g. Maltego) to gather names, dates, or terms.
  • Optimize size: Remove duplicates with sort | uniq.
  • Ethics: Conduct the selection within the scope of engagement, minimize the load.

Example of integration with Hydra:

Code:
hydra -l admin -P clean_wordlist.txt -t 2 -w 2 ssh://192.168.1.1

[h3]Automation of web application analysis[/h3]Web applications are like a magnet for pentesters: XSS, SQL injections, bad configs. Tools like Nuclei, OWASP ZAP or sqlmap help to quickly find holes.

[h4]Example: Nuclei for scanning[/h4]

Code:
nuclei -u https://example.com -t cves/ -o report.txt

Custom template for Nuclei:

Code:
id: custom-xss-check
info:
  name: Detect Reflected XSS
  severity: medium
requests:
  - method: GET
    path:
      - "{{BaseURL}}/search?q=<script>alert(1)</script>"
    matchers:
      - type: word
        words:
          - "<script>alert(1)</script>"
        part: body

CI/CD for automation:

Code:
name: Run Nuclei Scan
on: [push]
jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Run Nuclei
        run: nuclei -u https://example.com -t cves/ -o report.txt

Tip:
  • Use OWASP ZAP with API for active scanning.
  • Filter false positives in Nuclei.
  • Integrate with CI/CD for regular checks.
 
Top Bottom