Skip to main content

Overview

The SMBConnection class provides a unified, high-level interface for SMB communication that automatically handles protocol negotiation between SMB1, SMB2, and SMB3. It abstracts away protocol-specific details and provides a consistent API regardless of the underlying SMB version.

Class Definition

SMBConnection

Main class for SMB client operations with automatic protocol negotiation.
from impacket.smbconnection import SMBConnection

conn = SMBConnection(remoteName, remoteHost, myName=None, 
                      sess_port=445, timeout=60, 
                      preferredDialect=None)
remoteName
str
required
NetBIOS name of the remote host. Use '*SMBSERVER' for automatic detection, or provide the actual hostname.
remoteHost
str
required
IP address or hostname of the target server
myName
str
Local NetBIOS name. If None, uses the local hostname.
sess_port
int
default:"445"
SMB session port. Use 445 for direct TCP or 139 for NetBIOS
timeout
int
default:"60"
Connection timeout in seconds
preferredDialect
str | int
Preferred SMB dialect. Options:
  • SMB_DIALECT - SMB1 (NT LM 0.12)
  • SMB2_DIALECT_002 - SMB 2.0.2
  • SMB2_DIALECT_21 - SMB 2.1
  • SMB2_DIALECT_30 - SMB 3.0
  • SMB2_DIALECT_311 - SMB 3.1.1
If None, negotiates the highest supported version.

Authentication Methods

login()

Authenticate using NTLM.
conn.login(user, password, domain='', lmhash='', nthash='', 
           ntlmFallback=True)
user
str
required
Username for authentication
password
str
required
User password (not used if hashes are provided)
domain
str
default:"''"
Domain name for the account
lmhash
str
default:"''"
LM hash for pass-the-hash authentication (hex string)
nthash
str
default:"''"
NT hash for pass-the-hash authentication (hex string)
ntlmFallback
bool
default:"True"
Allow fallback to NTLMv1 if NTLMv2 fails (SMB1 only)
raises
SessionError
Raised if authentication fails

kerberosLogin()

Authenticate using Kerberos.
conn.kerberosLogin(user, password, domain='', lmhash='', nthash='',
                   aesKey='', kdcHost=None, TGT=None, TGS=None,
                   useCache=True)
user
str
required
Username for authentication
password
str
required
User password
domain
str
required
Domain name (required for Kerberos)
lmhash
str
default:"''"
LM hash for RC4-HMAC if AES not supported
nthash
str
default:"''"
NT hash for RC4-HMAC if AES not supported
aesKey
str
default:"''"
AES key (aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96)
kdcHost
str
Hostname or IP of the KDC. If None, uses DNS to resolve the domain.
TGT
dict
Pre-obtained Ticket Granting Ticket
TGS
dict
Pre-obtained Ticket Granting Service ticket
useCache
bool
default:"True"
Use credential cache for ticket lookup

File and Directory Operations

connectTree()

Connect to a network share.
tid = conn.connectTree(share)
share
str
required
Share name (e.g., 'ADMIN$', 'C$', 'IPC$')
return
int
Tree ID for use in subsequent operations

listPath()

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

createFile()

Create or open a file.
fid = conn.createFile(treeId, pathName, desiredAccess=GENERIC_ALL,
                       shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE,
                       creationOption=FILE_NON_DIRECTORY_FILE,
                       creationDisposition=FILE_OVERWRITE_IF,
                       fileAttributes=FILE_ATTRIBUTE_NORMAL)
treeId
int
required
Tree ID from connectTree()
pathName
str
required
Path to the file relative to share root
desiredAccess
int
default:"GENERIC_ALL"
Access mask (e.g., FILE_READ_DATA, FILE_WRITE_DATA, GENERIC_ALL)
shareMode
int
default:"FILE_SHARE_READ | FILE_SHARE_WRITE"
Share access mode
creationOption
int
default:"FILE_NON_DIRECTORY_FILE"
File creation options
creationDisposition
int
default:"FILE_OVERWRITE_IF"
Action to take if file exists
fileAttributes
int
default:"FILE_ATTRIBUTE_NORMAL"
File attributes to set
return
int
File ID (FID) for subsequent operations

openFile()

Open an existing file.
fid = conn.openFile(treeId, pathName, desiredAccess=FILE_READ_DATA,
                     shareMode=FILE_SHARE_READ)
treeId
int
required
Tree ID
pathName
str
required
Path to the file
desiredAccess
int
default:"FILE_READ_DATA"
Access rights requested
shareMode
int
default:"FILE_SHARE_READ"
Sharing mode
return
int
File ID for the opened file

readFile()

Read data from a file.
data = conn.readFile(treeId, fileId, offset=0, bytesToRead=None,
                      singleCall=True)
treeId
int
required
Tree ID
fileId
int
required
File ID from openFile() or createFile()
offset
int
default:"0"
Byte offset to start reading from
bytesToRead
int
Number of bytes to read. If None, reads maximum buffer size.
singleCall
bool
default:"True"
If True, reads only once. If False, continues reading until bytesToRead is satisfied.
return
bytes
Data read from the file

writeFile()

Write data to a file.
bytes_written = conn.writeFile(treeId, fileId, data, offset=0)
treeId
int
required
Tree ID
fileId
int
required
File ID
data
bytes
required
Data to write
offset
int
default:"0"
Byte offset to write at
return
int
Number of bytes written

closeFile()

Close an open file.
conn.closeFile(treeId, fileId)
treeId
int
required
Tree ID
fileId
int
required
File ID to close

deleteFile()

Delete a file from the share.
conn.deleteFile(shareName, pathName)
shareName
str
required
Share name
pathName
str
required
Path to the file to delete

getFile()

Download a file using a callback.
with open('local_file.txt', 'wb') as f:
    conn.getFile(shareName, pathName, f.write)
shareName
str
required
Share name
pathName
str
required
Remote file path
callback
callable
required
Function to call with file data chunks (receives bytes)
shareAccessMode
int
default:"FILE_SHARE_READ"
Share access mode

putFile()

Upload a file using a callback.
with open('local_file.txt', 'rb') as f:
    conn.putFile(shareName, pathName, f.read)
shareName
str
required
Share name
pathName
str
required
Remote file path
callback
callable
required
Function to call to get file data (receives int size, returns bytes)

createDirectory()

Create a directory.
conn.createDirectory(shareName, pathName)
shareName
str
required
Share name
pathName
str
required
Directory path to create

deleteDirectory()

Delete a directory.
conn.deleteDirectory(shareName, pathName)
shareName
str
required
Share name
pathName
str
required
Directory path to delete

rename()

Rename a file or directory.
conn.rename(shareName, oldPath, newPath)
shareName
str
required
Share name
oldPath
str
required
Current path
newPath
str
required
New path

Information Retrieval

listShares()

List available shares on the server.
shares = conn.listShares()
return
list[dict]
List of share dictionaries with keys like 'shi1_netname', 'shi1_type', 'shi1_remark'

getDialect()

Get the negotiated SMB dialect.
dialect = conn.getDialect()
return
str | int
The negotiated dialect (e.g., SMB2_DIALECT_311)

getServerName()

Get the server’s NetBIOS name.
server_name = conn.getServerName()
return
str
Server NetBIOS name

getServerDomain()

Get the server’s domain.
domain = conn.getServerDomain()
return
str
Server domain name

getServerOS()

Get the server’s operating system.
os_info = conn.getServerOS()
return
str
Operating system string (e.g., "Windows 10 Build 19041")

isGuestSession()

Check if logged in as guest.
is_guest = conn.isGuestSession()
return
bool
True if guest session, False otherwise

Named Pipe Operations

waitNamedPipe()

Wait for a named pipe to become available.
conn.waitNamedPipe(treeId, pipeName, timeout=5)
treeId
int
required
Tree ID (usually for IPC$ share)
pipeName
str
required
Name of the pipe (e.g., '\\PIPE\\srvsvc')
timeout
int
default:"5"
Timeout in seconds

transactNamedPipe()

Perform a transaction on a named pipe.
conn.transactNamedPipe(treeId, fileId, data, waitAnswer=True)
treeId
int
required
Tree ID
fileId
int
required
File ID of the opened pipe
data
bytes
required
Data to send
waitAnswer
bool
default:"True"
Wait for response

Connection Management

close()

Close the connection and log off.
conn.close()

logoff()

Log off from the server.
conn.logoff()

reconnect()

Reconnect using the same credentials.
conn.reconnect()

Usage Examples

Basic Connection and File Operations

from impacket.smbconnection import SMBConnection

# Connect to server (automatically negotiates SMB version)
conn = SMBConnection('WORKSTATION', '192.168.1.100')

# Authenticate
conn.login('admin', 'password', 'DOMAIN')

# List shares
shares = conn.listShares()
for share in shares:
    print(f"Share: {share['shi1_netname']} - {share['shi1_remark']}")

# List files
files = conn.listPath('C$', '/*')
for f in files:
    print(f"{f.get_longname()} ({f.get_filesize()} bytes)")

# Read a file
tid = conn.connectTree('C$')
fid = conn.openFile(tid, '/Windows/System32/drivers/etc/hosts',
                     FILE_READ_DATA, FILE_SHARE_READ)
data = conn.readFile(tid, fid)
conn.closeFile(tid, fid)

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

# Clean up
conn.close()

Upload and Download Files

from impacket.smbconnection import SMBConnection

conn = SMBConnection('*SMBSERVER', '192.168.1.100')
conn.login('user', 'pass')

# Upload a file
with open('local.txt', 'rb') as f:
    conn.putFile('share', '/remote.txt', f.read)

# Download a file
with open('downloaded.txt', 'wb') as f:
    conn.getFile('share', '/remote.txt', f.write)

conn.close()

Kerberos Authentication

from impacket.smbconnection import SMBConnection

conn = SMBConnection('DC01', '192.168.1.10')

# Authenticate with Kerberos
conn.kerberosLogin('admin', 'password', 'CORP.LOCAL',
                    kdcHost='dc01.corp.local')

# Perform operations
shares = conn.listShares()
for share in shares:
    print(share['shi1_netname'])

conn.close()

Pass-the-Hash

from impacket.smbconnection import SMBConnection

conn = SMBConnection('*SMBSERVER', '192.168.1.100')

# Authenticate using NTLM hash
conn.login('administrator', '', 'WORKGROUP',
           lmhash='aad3b435b51404eeaad3b435b51404ee',
           nthash='8846f7eaee8fb117ad06bdd830b7586c')

tid = conn.connectTree('ADMIN$')
files = conn.listPath('ADMIN$', '/*')
conn.close()

Working with Named Pipes (RPC)

from impacket.smbconnection import SMBConnection
from impacket.dcerpc.v5 import transport

conn = SMBConnection('*SMBSERVER', '192.168.1.100')
conn.login('admin', 'password')

# Use SMBConnection for RPC transport
rpctransport = transport.SMBTransport('192.168.1.100',
                                       filename=r'\pipe\samr',
                                       smb_connection=conn)

dce = rpctransport.get_dce_rpc()
dce.connect()
# ... perform RPC operations ...

conn.close()

Error Handling

from impacket.smbconnection import SMBConnection, SessionError
from impacket.nt_errors import STATUS_LOGON_FAILURE, STATUS_OBJECT_NAME_NOT_FOUND

try:
    conn = SMBConnection('*SMBSERVER', '192.168.1.100')
    conn.login('user', 'wrongpass')
except SessionError as e:
    error_code = e.getErrorCode()
    
    if error_code == STATUS_LOGON_FAILURE:
        print("Invalid credentials")
    else:
        print(f"SMB Error: {e.getErrorString()}")

See Also

  • SMB - Low-level SMB1 implementation
  • SMB3 - Low-level SMB2/SMB3 implementation
  • NTLM - NTLM authentication

Build docs developers (and LLMs) love