Skip to main content

Overview

The smb module provides a complete implementation of the SMB (Server Message Block) protocol version 1. This module handles low-level SMB packet construction, authentication, file operations, and named pipe communication.

Key Classes

SMB

Main class for SMB protocol implementation.
from impacket import smb

conn = smb.SMB(remote_name, remote_host)
conn.login(user, password, domain)
remote_name
str
required
The NetBIOS name of the remote host. Use '*SMBSERVER' for auto-detection.
remote_host
str
required
IP address or hostname of the remote server
my_name
str
Local NetBIOS name. Defaults to local hostname if not specified.
sess_port
int
default:"139"
Port number for NetBIOS session service
timeout
int
default:"60"
Connection timeout in seconds

Methods

login()

Authenticate to the SMB server using NTLM.
conn.login(user, password, domain='', lmhash='', nthash='')
user
str
required
Username for authentication
password
str
required
Password for authentication (not used if hashes provided)
domain
str
default:"''"
Domain name for authentication
lmhash
str
default:"''"
LM hash for pass-the-hash authentication
nthash
str
default:"''"
NT hash for pass-the-hash authentication
return
None
Raises SessionError if authentication fails

connect_tree()

Connect to a shared resource on the server.
tid = conn.connect_tree(share)
share
str
required
UNC path to the share (e.g., '\\\\server\\share')
return
int
Tree ID (TID) used for subsequent file operations

list_path()

List files and directories in a share.
files = conn.list_path(shareName, path, password=None)
shareName
str
required
Name of the share to list
path
str
required
Path relative to the share root (e.g., '*' for all files)
password
str
Password for password-protected shares
return
list[SharedFile]
List of SharedFile objects containing file information

open()

Open or create a file on the share.
fid = conn.open(tid, path, desired_access, share_mode, 
                creation_options, creation_disposition, 
                file_attributes)
tid
int
required
Tree ID from connect_tree()
path
str
required
Path to the file relative to share root
desired_access
int
required
Access mask specifying desired operations (e.g., FILE_READ_DATA, FILE_WRITE_DATA)
share_mode
int
required
Share mode flags (e.g., FILE_SHARE_READ, FILE_SHARE_WRITE)
creation_options
int
required
Creation options (e.g., FILE_NON_DIRECTORY_FILE)
creation_disposition
int
required
Creation disposition (e.g., FILE_OPEN, FILE_CREATE, FILE_OVERWRITE_IF)
file_attributes
int
required
File attributes (e.g., ATTR_NORMAL, ATTR_READONLY)
return
int
File ID (FID) used for read/write operations

read_andx()

Read data from an open file.
data = conn.read_andx(tid, fid, offset=0, max_size=None)
tid
int
required
Tree ID
fid
int
required
File ID from open()
offset
int
default:"0"
Byte offset to start reading from
max_size
int
Maximum bytes to read. Defaults to server’s max buffer size.
return
bytes
Data read from the file

write_andx()

Write data to an open file.
bytes_written = conn.write_andx(tid, fid, data, offset=0)
tid
int
required
Tree ID
fid
int
required
File ID from open()
data
bytes
required
Data to write to the file
offset
int
default:"0"
Byte offset to start writing at
return
int
Number of bytes written

close()

Close an open file.
conn.close(tid, fid)
tid
int
required
Tree ID
fid
int
required
File ID to close

logoff()

Log off from the SMB server.
conn.logoff()

Constants

File Attributes

ATTR_READONLY = 0x001    # Read-only file
ATTR_HIDDEN = 0x002      # Hidden file
ATTR_SYSTEM = 0x004      # System file
ATTR_DIRECTORY = 0x010   # Directory
ATTR_ARCHIVE = 0x020     # Archive flag
ATTR_NORMAL = 0x080      # Normal file
ATTR_TEMPORARY = 0x100   # Temporary file
ATTR_COMPRESSED = 0x800  # Compressed file

Access Masks

FILE_READ_DATA = 0x00000001       # Read file data
FILE_WRITE_DATA = 0x00000002      # Write file data
FILE_APPEND_DATA = 0x00000004     # Append to file
FILE_READ_EA = 0x00000008         # Read extended attributes
FILE_WRITE_EA = 0x00000010        # Write extended attributes
FILE_EXECUTE = 0x00000020         # Execute file
FILE_READ_ATTRIBUTES = 0x00000080 # Read file attributes
FILE_WRITE_ATTRIBUTES = 0x00000100 # Write file attributes
DELETE = 0x00010000               # Delete file
GENERIC_READ = 0x80000000         # Generic read access
GENERIC_WRITE = 0x40000000        # Generic write access
GENERIC_ALL = 0x10000000          # All access rights

Share Access Modes

FILE_SHARE_READ = 0x00000001      # Allow concurrent read access
FILE_SHARE_WRITE = 0x00000002     # Allow concurrent write access
FILE_SHARE_DELETE = 0x00000004    # Allow concurrent delete access

Creation Disposition

FILE_SUPERSEDE = 0x00000000    # Replace file if exists, create if not
FILE_OPEN = 0x00000001         # Open existing file only
FILE_CREATE = 0x00000002       # Create new file only
FILE_OPEN_IF = 0x00000003      # Open if exists, create if not
FILE_OVERWRITE = 0x00000004    # Overwrite existing file only
FILE_OVERWRITE_IF = 0x00000005 # Overwrite if exists, create if not

Supporting Classes

SharedFile

Represents file information returned by list_path().
get_longname()
str
Returns the full filename
get_shortname()
str
Returns the 8.3 short filename
get_filesize()
int
Returns file size in bytes
is_directory()
bool
Returns True if item is a directory
is_readonly()
bool
Returns True if file is read-only
is_hidden()
bool
Returns True if file is hidden
get_ctime_epoch()
int
Returns creation time as Unix timestamp
get_mtime_epoch()
int
Returns modification time as Unix timestamp
get_atime_epoch()
int
Returns access time as Unix timestamp

SessionError

Exception raised when SMB operations fail.
try:
    conn.login(user, password)
except smb.SessionError as e:
    print(f"Error: {e}")
    error_code = e.get_error_code()
get_error_code()
int
Returns the SMB error code
get_error_class()
int
Returns the error class

Usage Examples

Basic File Operations

from impacket import smb
from impacket.smb import FILE_OPEN, FILE_SHARE_READ

# Connect to server
conn = smb.SMB('*SMBSERVER', '192.168.1.100')
conn.login('user', 'password', 'DOMAIN')

# Connect to share
tid = conn.connect_tree('\\\\192.168.1.100\\share')

# List files
files = conn.list_path('share', '*')
for f in files:
    print(f"{f.get_longname()} - {f.get_filesize()} bytes")

# Read a file
fid = conn.open(tid, 'example.txt', smb.FILE_READ_DATA, 
                FILE_SHARE_READ, smb.FILE_NON_DIRECTORY_FILE,
                FILE_OPEN, smb.ATTR_NORMAL)
data = conn.read_andx(tid, fid)
conn.close(tid, fid)

print(data.decode('utf-8'))

# Clean up
conn.logoff()

Writing Files

from impacket import smb

conn = smb.SMB('*SMBSERVER', '192.168.1.100')
conn.login('user', 'password')
tid = conn.connect_tree('\\\\192.168.1.100\\share')

# Create and write to file
fid = conn.open(tid, 'output.txt', 
                smb.FILE_WRITE_DATA | smb.FILE_READ_DATA,
                smb.FILE_SHARE_READ, smb.FILE_NON_DIRECTORY_FILE,
                smb.FILE_OVERWRITE_IF, smb.ATTR_NORMAL)

data = b"Hello, SMB World!"
conn.write_andx(tid, fid, data)
conn.close(tid, fid)

conn.logoff()

Pass-the-Hash Authentication

from impacket import smb
import hashlib

conn = smb.SMB('*SMBSERVER', '192.168.1.100')

# Authenticate using NTLM hash
lmhash = 'aad3b435b51404eeaad3b435b51404ee'
nthash = '8846f7eaee8fb117ad06bdd830b7586c'

conn.login('admin', '', domain='CORP', lmhash=lmhash, nthash=nthash)
tid = conn.connect_tree('\\\\192.168.1.100\\C$')

# Now you can perform operations
files = conn.list_path('C$', '*')
conn.logoff()

Error Handling

from impacket import smb
from impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_OBJECT_NAME_NOT_FOUND

try:
    conn = smb.SMB('*SMBSERVER', '192.168.1.100')
    conn.login('user', 'wrongpassword')
except smb.SessionError as e:
    if e.get_error_code() == STATUS_ACCESS_DENIED:
        print("Access denied - check credentials")
    else:
        print(f"SMB Error: {e}")

Helper Functions

Time Conversion

from impacket import smb
import time

# Convert POSIX timestamp to Windows FILETIME
posix_time = int(time.time())
filetime = smb.POSIXtoFT(posix_time)

# Convert FILETIME to POSIX timestamp
posix_time = smb.FTtoPOSIX(filetime)

See Also

  • SMBConnection - High-level SMB client wrapper
  • SMB3 - SMB2/SMB3 protocol implementation
  • NTLM - NTLM authentication helpers

Build docs developers (and LLMs) love