> For the complete documentation index, see [llms.txt](https://www.impacket.wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.impacket.wiki/reference/library-api/smb-and-netbios/smbconnection.md).

# SMBConnection

> High-level SMB client wrapper supporting SMB1, SMB2, and SMB3

## 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.

```python
from impacket.smbconnection import SMBConnection

conn = SMBConnection(remoteName, remoteHost, myName=None,
                      sess_port=445, timeout=60,
                      preferredDialect=None)
```

* **Parameter `remoteName`** **`str`:** NetBIOS name of the remote host. Use `'*SMBSERVER'` for automatic detection, or provide the actual hostname.
* **Parameter `remoteHost`** **`str`:** IP address or hostname of the target server
* **Parameter `myName`** **`str`:** Local NetBIOS name. If `None`, uses the local hostname.
* **Parameter `sess_port`** **`int`:** SMB session port. Use `445` for direct TCP or `139` for NetBIOS
* **Parameter `timeout`** **`int`:** Connection timeout in seconds
* **Parameter `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.

```python
conn.login(user, password, domain='', lmhash='', nthash='',
           ntlmFallback=True)
```

* **Parameter `user`** **`str`:** Username for authentication
* **Parameter `password`** **`str`:** User password (not used if hashes are provided)
* **Parameter `domain`** **`str`:** Domain name for the account
* **Parameter `lmhash`** **`str`:** LM hash for pass-the-hash authentication (hex string)
* **Parameter `nthash`** **`str`:** NT hash for pass-the-hash authentication (hex string)
* **Parameter `ntlmFallback`** **`bool`:** Allow fallback to NTLMv1 if NTLMv2 fails (SMB1 only)
* **Returns `raises`** **`SessionError`:** Raised if authentication fails

### kerberosLogin()

Authenticate using Kerberos.

```python
conn.kerberosLogin(user, password, domain='', lmhash='', nthash='',
                   aesKey='', kdcHost=None, TGT=None, TGS=None,
                   useCache=True)
```

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

## File and Directory Operations

### connectTree()

Connect to a network share.

```python
tid = conn.connectTree(share)
```

* **Parameter `share`** **`str`:** Share name (e.g., `'ADMIN$'`, `'C$'`, `'IPC$'`)
* **Returns `return`** **`int`:** Tree ID for use in subsequent operations

### listPath()

List files and directories in a share.

```python
files = conn.listPath(shareName, path, password=None)
```

* **Parameter `shareName`** **`str`:** Name of the share to list
* **Parameter `path`** **`str`:** Path pattern (e.g., `'*'` for all files, `'*.txt'` for text files)
* **Parameter `password`** **`str`:** Password for password-protected shares
* **Returns `return`** **`list[SharedFile]`:** List of `SharedFile` objects

### createFile()

Create or open a file.

```python
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)
```

* **Parameter `treeId`** **`int`:** Tree ID from `connectTree()`
* **Parameter `pathName`** **`str`:** Path to the file relative to share root
* **Parameter `desiredAccess`** **`int`:** Access mask (e.g., `FILE_READ_DATA`, `FILE_WRITE_DATA`, `GENERIC_ALL`)
* **Parameter `shareMode`** **`int`:** Share access mode
* **Parameter `creationOption`** **`int`:** File creation options
* **Parameter `creationDisposition`** **`int`:** Action to take if file exists
* **Parameter `fileAttributes`** **`int`:** File attributes to set
* **Returns `return`** **`int`:** File ID (FID) for subsequent operations

### openFile()

Open an existing file.

```python
fid = conn.openFile(treeId, pathName, desiredAccess=FILE_READ_DATA,
                     shareMode=FILE_SHARE_READ)
```

* **Parameter `treeId`** **`int`:** Tree ID
* **Parameter `pathName`** **`str`:** Path to the file
* **Parameter `desiredAccess`** **`int`:** Access rights requested
* **Parameter `shareMode`** **`int`:** Sharing mode
* **Returns `return`** **`int`:** File ID for the opened file

### readFile()

Read data from a file.

```python
data = conn.readFile(treeId, fileId, offset=0, bytesToRead=None,
                      singleCall=True)
```

* **Parameter `treeId`** **`int`:** Tree ID
* **Parameter `fileId`** **`int`:** File ID from `openFile()` or `createFile()`
* **Parameter `offset`** **`int`:** Byte offset to start reading from
* **Parameter `bytesToRead`** **`int`:** Number of bytes to read. If `None`, reads maximum buffer size.
* **Parameter `singleCall`** **`bool`:** If `True`, reads only once. If `False`, continues reading until `bytesToRead` is satisfied.
* **Returns `return`** **`bytes`:** Data read from the file

### writeFile()

Write data to a file.

```python
bytes_written = conn.writeFile(treeId, fileId, data, offset=0)
```

* **Parameter `treeId`** **`int`:** Tree ID
* **Parameter `fileId`** **`int`:** File ID
* **Parameter `data`** **`bytes`:** Data to write
* **Parameter `offset`** **`int`:** Byte offset to write at
* **Returns `return`** **`int`:** Number of bytes written

### closeFile()

Close an open file.

```python
conn.closeFile(treeId, fileId)
```

* **Parameter `treeId`** **`int`:** Tree ID
* **Parameter `fileId`** **`int`:** File ID to close

### deleteFile()

Delete a file from the share.

```python
conn.deleteFile(shareName, pathName)
```

* **Parameter `shareName`** **`str`:** Share name
* **Parameter `pathName`** **`str`:** Path to the file to delete

### getFile()

Download a file using a callback.

```python
with open('local_file.txt', 'wb') as f:
    conn.getFile(shareName, pathName, f.write)
```

* **Parameter `shareName`** **`str`:** Share name
* **Parameter `pathName`** **`str`:** Remote file path
* **Parameter `callback`** **`callable`:** Function to call with file data chunks (receives bytes)
* **Parameter `shareAccessMode`** **`int`:** Share access mode

### putFile()

Upload a file using a callback.

```python
with open('local_file.txt', 'rb') as f:
    conn.putFile(shareName, pathName, f.read)
```

* **Parameter `shareName`** **`str`:** Share name
* **Parameter `pathName`** **`str`:** Remote file path
* **Parameter `callback`** **`callable`:** Function to call to get file data (receives int size, returns bytes)

### createDirectory()

Create a directory.

```python
conn.createDirectory(shareName, pathName)
```

* **Parameter `shareName`** **`str`:** Share name
* **Parameter `pathName`** **`str`:** Directory path to create

### deleteDirectory()

Delete a directory.

```python
conn.deleteDirectory(shareName, pathName)
```

* **Parameter `shareName`** **`str`:** Share name
* **Parameter `pathName`** **`str`:** Directory path to delete

### rename()

Rename a file or directory.

```python
conn.rename(shareName, oldPath, newPath)
```

* **Parameter `shareName`** **`str`:** Share name
* **Parameter `oldPath`** **`str`:** Current path
* **Parameter `newPath`** **`str`:** New path

## Information Retrieval

### listShares()

List available shares on the server.

```python
shares = conn.listShares()
```

* **Returns `return`** **`list[dict]`:** List of share dictionaries with keys like `'shi1_netname'`, `'shi1_type'`, `'shi1_remark'`

### getDialect()

Get the negotiated SMB dialect.

```python
dialect = conn.getDialect()
```

* **Returns `return`** **`str | int`:** The negotiated dialect (e.g., `SMB2_DIALECT_311`)

### getServerName()

Get the server's NetBIOS name.

```python
server_name = conn.getServerName()
```

* **Returns `return`** **`str`:** Server NetBIOS name

### getServerDomain()

Get the server's domain.

```python
domain = conn.getServerDomain()
```

* **Returns `return`** **`str`:** Server domain name

### getServerOS()

Get the server's operating system.

```python
os_info = conn.getServerOS()
```

* **Returns `return`** **`str`:** Operating system string (e.g., `"Windows 10 Build 19041"`)

### isGuestSession()

Check if logged in as guest.

```python
is_guest = conn.isGuestSession()
```

* **Returns `return`** **`bool`:** `True` if guest session, `False` otherwise

## Named Pipe Operations

### waitNamedPipe()

Wait for a named pipe to become available.

```python
conn.waitNamedPipe(treeId, pipeName, timeout=5)
```

* **Parameter `treeId`** **`int`:** Tree ID (usually for IPC$ share)
* **Parameter `pipeName`** **`str`:** Name of the pipe (e.g., `'\\PIPE\\srvsvc'`)
* **Parameter `timeout`** **`int`:** Timeout in seconds

### transactNamedPipe()

Perform a transaction on a named pipe.

```python
conn.transactNamedPipe(treeId, fileId, data, waitAnswer=True)
```

* **Parameter `treeId`** **`int`:** Tree ID
* **Parameter `fileId`** **`int`:** File ID of the opened pipe
* **Parameter `data`** **`bytes`:** Data to send
* **Parameter `waitAnswer`** **`bool`:** Wait for response

## Connection Management

### close()

Close the connection and log off.

```python
conn.close()
```

### logoff()

Log off from the server.

```python
conn.logoff()
```

### reconnect()

Reconnect using the same credentials.

```python
conn.reconnect()
```

## Usage Examples

### Basic Connection and File Operations

```python
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

```python
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

```python
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

```python
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)

```python
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

```python
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](/reference/library-api/smb-and-netbios/smb.md) - Low-level SMB1 implementation
* [SMB3](/reference/library-api/smb-and-netbios/smbconnection.md) - Low-level SMB2/SMB3 implementation
* [NTLM](https://github.com/ThatTotallyRealMyth/Impacket-Documentation/blob/main/reference/library-api/credentials-and-storage/ntlm.md) - NTLM authentication


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://www.impacket.wiki/reference/library-api/smb-and-netbios/smbconnection.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
