Scripting Basics: Difference between revisions

From HackOps
Jump to navigation Jump to search
Created page with "== Scripting Basics == Scripting automates repetitive tasks, accelerates testing, and glues tools together. A single script can gather data, transform output, launch exploits, and log results in seconds. The three core environments are Bash, Python, and PowerShell; each dominates a different operating system family yet follows the same logic: read input → process → act. === Common Techniques === Parsing tool output and extracting key fields with regular expression..."
 
 
(3 intermediate revisions by the same user not shown)
Line 5: Line 5:
=== Common Techniques ===
=== Common Techniques ===


Parsing tool output and extracting key fields with regular expressions or JSON‐filters
* Parsing tool output and extracting key fields with regular expressions or JSON‐filters
Looping through wordlists, IP ranges, or file paths to launch bulk scans
* Looping through wordlists, IP ranges, or file paths to launch bulk scans
Wrapping exploits in functions for re-use across targets
* Wrapping exploits in functions for re-use across targets
Chaining commands with pipes to form one-liner workflows
* Chaining commands with pipes to form one-liner workflows
Reading STDIN / STDOUT for live data transformation
* Reading STDIN / STDOUT for live data transformation
Generating payloads dynamically (reverse shells, encoded scripts, shellcode)
* Generating payloads dynamically (reverse shells, encoded scripts, shellcode)
Logging actions and timestamps to CSV or SQLite for later reporting
* Logging actions and timestamps to CSV or SQLite for later reporting
Using environment variables and arguments to create portable modules
* Using environment variables and arguments to create portable modules
Invoking REST APIs to pull scope lists, asset inventories, or vulnerability feeds
* Invoking REST APIs to pull scope lists, asset inventories, or vulnerability feeds
Scheduling scripts via cron, Task Scheduler, or at jobs for continuous monitoring
* Scheduling scripts via cron, Task Scheduler, or at jobs for continuous monitoring
 
=== Tools ===
=== Tools ===


Line 30: Line 31:
* [[tmux]] / [[screen]] (terminal multiplexers that keep long-running scripts alive)
* [[tmux]] / [[screen]] (terminal multiplexers that keep long-running scripts alive)
=== Quick Examples ===
=== Quick Examples ===
==== Bash ====
This script scans a given subnet for live hosts by sending ICMP echo requests (ping) and prints responding IP addresses.
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
#!/bin/bash
# Loop through IP addresses 1 to 254 in a subnet
for ip in $(seq 1 254); do
    # Send 1 ping (-c 1) to each IP in the given subnet (passed as $1)
    # Example: if $1 = 192.168.1, it pings 192.168.1.1 to 192.168.1.254
    ping -c 1 $1.$ip |
    # Look for lines in the ping output that contain "64 bytes"
    grep "64 bytes" |


Bash one-liner: scan subnet and log live hosts
    # Extract the 4th field (which contains the IP with a colon at the end)
    cut -d " " -f 4 |


    # Remove the trailing colon from the IP
    tr -d ":" &
done
# Notes:
# - $(...) is used instead of backticks \`...\` (modern syntax)
# - '&' runs each ping in the background for speed
# - This script prints a list of live hosts in the subnet
# - Usage: ./script.sh 192.168.1
</syntaxhighlight>
This script performs a fast parallel ping sweep across a /24 subnet and logs all responsive IPs to a CSV file.
<syntaxhighlight lang="bash">
# Scan a subnet (10.10.10.1–254) and log live hosts to a CSV file
# Loop over all IPs in the subnet
for ip in 10.10.10.{1..254}; do
for ip in 10.10.10.{1..254}; do
ping -c1 -W1 $ip &>/dev/null && echo "$ip,up" >> live.csv &
 
done; wait
  # Ping each IP once (-c1), wait max 1 second for reply (-W1)
  # Suppress output (&>/dev/null), and if host responds, log to file
  ping -c1 -W1 $ip &>/dev/null && echo "$ip,up" >> live.csv &
 
done
 
# Wait for all background pings to finish
wait
</syntaxhighlight>
</syntaxhighlight>
==== Python ====
This script extracts and displays open ports for each host from a parsed Nmap XML scan report.


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# Python: parse nmap XML and list open ports per host
# Parse Nmap XML output and print open ports per host
import xml.etree.ElementTree as ET
 
import sys
import xml.etree.ElementTree as ET # XML parser from standard library
import sys # (commonly used for CLI arguments, not used here)


# Load and parse the Nmap scan file
tree = ET.parse('scan.xml')
tree = ET.parse('scan.xml')
# Loop through each host in the scan
for host in tree.findall('.//host'):
for host in tree.findall('.//host'):
    # Extract the IP address of the host
     addr = host.find('address').attrib['addr']
     addr = host.find('address').attrib['addr']
     ports = [p.attrib['portid'] for p in host.findall('.//port[state/@state="open"]')]
 
    # Collect all open port numbers for this host
     ports = [
        p.attrib['portid']
        for p in host.findall('.//port[state/@state="open"]')
    ]
 
    # Print IP address and a comma-separated list of open ports
     print(addr, ','.join(ports))
     print(addr, ','.join(ports))
</syntaxhighlight>
</syntaxhighlight>
==== PowerShell ====
This script queries all computer objects in Active Directory and checks which ones respond to ping.


<syntaxhighlight lang="powershell">
<syntaxhighlight lang="powershell">
# PowerShell: pull AD computer names and ping each
# Get all Active Directory computer names and test if they are reachable
 
# Query all computer objects in Active Directory
Get-ADComputer -Filter * |
Get-ADComputer -Filter * |
    # Extract only the 'Name' field (hostnames)
     Select-Object -Expand Name |
     Select-Object -Expand Name |
    # For each hostname, test network connectivity
     ForEach-Object {
     ForEach-Object {
         if (Test-Connection -Quiet $_) {
         if (Test-Connection -Quiet $_) {
            # If reachable, print confirmation message
             "$_ reachable"
             "$_ reachable"
         }
         }
     }
     }
# Notes:
# Test-Connection is equivalent to 'ping'
# -Quiet returns only $true or $false (no output text)
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 21:41, 17 May 2025

Scripting Basics

Scripting automates repetitive tasks, accelerates testing, and glues tools together. A single script can gather data, transform output, launch exploits, and log results in seconds. The three core environments are Bash, Python, and PowerShell; each dominates a different operating system family yet follows the same logic: read input → process → act.

Common Techniques

  • Parsing tool output and extracting key fields with regular expressions or JSON‐filters
  • Looping through wordlists, IP ranges, or file paths to launch bulk scans
  • Wrapping exploits in functions for re-use across targets
  • Chaining commands with pipes to form one-liner workflows
  • Reading STDIN / STDOUT for live data transformation
  • Generating payloads dynamically (reverse shells, encoded scripts, shellcode)
  • Logging actions and timestamps to CSV or SQLite for later reporting
  • Using environment variables and arguments to create portable modules
  • Invoking REST APIs to pull scope lists, asset inventories, or vulnerability feeds
  • Scheduling scripts via cron, Task Scheduler, or at jobs for continuous monitoring

Tools

  • Bash (POSIX shell with extensive native command set)
  • Python (multiplatform language with libraries such as subprocess, requests, and pwntools)
  • PowerShell (object-centric shell for Windows and cross-platform automation)
  • jq (lightweight JSON processor ideal for API or tool output)
  • awk & sed (stream editors for quick text manipulation)
  • Expect (automates interactive CLI sessions)
  • Impacket scripts (Python collection for network exploitation)
  • pwntools (CTF-oriented Python framework for exploit development)
  • psutil (Python library for process and system information)
  • Invoke-Obfuscation (PowerShell module for payload transformation)
  • Cron / Task Scheduler (native schedulers for timed script execution)
  • tmux / screen (terminal multiplexers that keep long-running scripts alive)

Quick Examples

Bash

This script scans a given subnet for live hosts by sending ICMP echo requests (ping) and prints responding IP addresses.

#!/bin/bash

# Loop through IP addresses 1 to 254 in a subnet
for ip in $(seq 1 254); do

    # Send 1 ping (-c 1) to each IP in the given subnet (passed as $1)
    # Example: if $1 = 192.168.1, it pings 192.168.1.1 to 192.168.1.254
    ping -c 1 $1.$ip |

    # Look for lines in the ping output that contain "64 bytes"
    grep "64 bytes" |

    # Extract the 4th field (which contains the IP with a colon at the end)
    cut -d " " -f 4 |

    # Remove the trailing colon from the IP
    tr -d ":" &

done

# Notes:
# - $(...) is used instead of backticks \`...\` (modern syntax)
# - '&' runs each ping in the background for speed
# - This script prints a list of live hosts in the subnet
# - Usage: ./script.sh 192.168.1

This script performs a fast parallel ping sweep across a /24 subnet and logs all responsive IPs to a CSV file.

# Scan a subnet (10.10.10.1–254) and log live hosts to a CSV file

# Loop over all IPs in the subnet
for ip in 10.10.10.{1..254}; do

  # Ping each IP once (-c1), wait max 1 second for reply (-W1)
  # Suppress output (&>/dev/null), and if host responds, log to file
  ping -c1 -W1 $ip &>/dev/null && echo "$ip,up" >> live.csv &

done

# Wait for all background pings to finish
wait

Python

This script extracts and displays open ports for each host from a parsed Nmap XML scan report.

# Parse Nmap XML output and print open ports per host

import xml.etree.ElementTree as ET  # XML parser from standard library
import sys  # (commonly used for CLI arguments, not used here)

# Load and parse the Nmap scan file
tree = ET.parse('scan.xml')

# Loop through each host in the scan
for host in tree.findall('.//host'):

    # Extract the IP address of the host
    addr = host.find('address').attrib['addr']

    # Collect all open port numbers for this host
    ports = [
        p.attrib['portid']
        for p in host.findall('.//port[state/@state="open"]')
    ]

    # Print IP address and a comma-separated list of open ports
    print(addr, ','.join(ports))

PowerShell

This script queries all computer objects in Active Directory and checks which ones respond to ping.

# Get all Active Directory computer names and test if they are reachable

# Query all computer objects in Active Directory
Get-ADComputer -Filter * |

    # Extract only the 'Name' field (hostnames)
    Select-Object -Expand Name |

    # For each hostname, test network connectivity
    ForEach-Object {
        if (Test-Connection -Quiet $_) {
            # If reachable, print confirmation message
            "$_ reachable"
        }
    }

# Notes:
# Test-Connection is equivalent to 'ping'
# -Quiet returns only $true or $false (no output text)