Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/fortra/impacket/llms.txt

Use this file to discover all available pages before exploring further.

Your First Impacket Script

This guide walks you through creating a simple script that connects to a remote SMB server and lists available shares.
1

Import Impacket

Start by importing the necessary modules:
from impacket.smbconnection import SMBConnection
from impacket.examples import logger
import logging
2

Create an SMB Connection

Establish a connection to the target server:
# Initialize connection
server_name = "192.168.1.100"
server_ip = "192.168.1.100"

# Create SMBConnection instance
smbConn = SMBConnection(server_name, server_ip, sess_port=445)
The sess_port parameter defaults to 445 (SMB over TCP). Use 139 for SMB over NetBIOS.
3

Authenticate

Log in with credentials:
username = "admin"
password = "password123"
domain = "WORKGROUP"

# Login with username and password
smbConn.login(username, password, domain)
4

Interact with SMB

Once authenticated, you can interact with the server:
# List available shares
shares = smbConn.listShares()

for share in shares:
    print(f"Share: {share['shi1_netname'][:-1]}")
    print(f"  Type: {share['shi1_type']}")
    print(f"  Comment: {share['shi1_remark'][:-1]}")
5

Clean Up

Always close the connection when done:
smbConn.logoff()

Complete Example

Here’s a complete working example that lists SMB shares:
smb_list_shares.py
from impacket.smbconnection import SMBConnection
import sys
import logging

def list_shares(target_ip, username, password, domain=''):
    """
    Connect to an SMB server and list available shares.
    
    Args:
        target_ip: IP address of the target server
        username: Username for authentication
        password: Password for authentication
        domain: Domain name (optional)
    """
    try:
        # Create connection
        smbConn = SMBConnection(target_ip, target_ip, sess_port=445)
        
        # Authenticate
        smbConn.login(username, password, domain)
        print(f"[+] Successfully authenticated to {target_ip}")
        
        # List shares
        print("\n[*] Available shares:")
        shares = smbConn.listShares()
        
        for share in shares:
            share_name = share['shi1_netname'][:-1]
            share_type = share['shi1_type']
            share_comment = share['shi1_remark'][:-1]
            
            print(f"\n  Share: {share_name}")
            print(f"    Type: {share_type}")
            print(f"    Comment: {share_comment}")
        
        # Clean up
        smbConn.logoff()
        print("\n[+] Connection closed")
        
    except Exception as e:
        print(f"[!] Error: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print(f"Usage: {sys.argv[0]} <target_ip> <username> <password>")
        sys.exit(1)
    
    target = sys.argv[1]
    user = sys.argv[2]
    passwd = sys.argv[3]
    
    list_shares(target, user, passwd)

Running the Example

python smb_list_shares.py 192.168.1.100 admin password123

Authentication Methods

Impacket supports multiple authentication methods:
Standard password authentication:
smbConn.login(username, password, domain)

Working with DCERPC

Impacket provides powerful DCERPC capabilities. Here’s an example using the DCERPCTransportFactory:
detect_architecture.py
from impacket.dcerpc.v5.transport import DCERPCTransportFactory
from impacket.dcerpc.v5.epm import MSRPC_UUID_PORTMAP
from impacket.dcerpc.v5.rpcrt import DCERPCException

def detect_architecture(target_ip):
    """
    Detect if target system is 32-bit or 64-bit.
    Based on getArch.py example.
    """
    NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0')
    
    try:
        # Create transport
        stringBinding = f'ncacn_ip_tcp:{target_ip}[135]'
        transport = DCERPCTransportFactory(stringBinding)
        transport.set_connect_timeout(5)
        
        # Connect and bind
        dce = transport.get_dce_rpc()
        dce.connect()
        
        try:
            dce.bind(MSRPC_UUID_PORTMAP, transfer_syntax=NDR64Syntax)
            print(f"{target_ip} is 64-bit")
        except DCERPCException as e:
            if 'syntaxes_not_supported' in str(e):
                print(f"{target_ip} is 32-bit")
            else:
                raise
        
        dce.disconnect()
        
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    detect_architecture("192.168.1.100")

Common Patterns

Error Handling

Always implement proper error handling:
from impacket.smbconnection import SessionError

try:
    smbConn = SMBConnection(target, target_ip)
    smbConn.login(username, password, domain)
    # Your code here
except SessionError as e:
    print(f"SMB Session Error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
finally:
    if smbConn:
        smbConn.logoff()

Using the Examples Logger

Impacket includes a logger utility for consistent output:
from impacket.examples import logger
import logging

# Initialize logger with timestamp and debug options
logger.init(ts=True, debug=True)

# Use logging
logging.info("Connection established")
logging.error("Failed to authenticate")
logging.debug("Detailed debug information")

Next Steps

Authentication

Learn about NTLM, Kerberos, and credential formats

SMB Protocol

Dive deeper into SMB/CIFS functionality

MS-RPC

Explore MSRPC and DCERPC capabilities

Examples

Browse complete example scripts and use cases
Always ensure you have proper authorization before connecting to remote systems. Unauthorized access is illegal.