### Install smbprotocol Prerequisites Source: https://github.com/jborean93/smbprotocol/blob/master/README.md Command to install the necessary prerequisites for testing the smbprotocol module in the current environment. ```bash # Install in current environment. ``` -------------------------------- ### Install smbprotocol Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Install the smbprotocol library using pip. For Kerberos support on Linux, include the [kerberos] extra. ```bash pip install smbprotocol # With Kerberos support (Linux) pip install smbprotocol[kerberos] ``` -------------------------------- ### Open File Example (Markdown) Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/README.md Illustrates opening a file on a remote SMB share using the high-level API. This example is extracted from the function documentation. ```python with smbclient.open_file(r'\\server\share\file.txt') as f: data = f.read() ``` -------------------------------- ### Setup Samba Server for Integration Tests Source: https://github.com/jborean93/smbprotocol/blob/master/README.md Configures a Samba server and sets the required environment variables for integration tests. Ensure you have Docker installed. ```bash source ./build_helpers/lib.sh lib::setup::smb_server ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/jborean93/smbprotocol/blob/master/README.md Installs the necessary development dependencies and the project in editable mode. ```bash pip install -r requirements-dev.txt pip install -e . ``` -------------------------------- ### Low-Level API Example Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Demonstrates the complete lifecycle of connecting to a server, establishing a session, connecting to a share, opening a file, reading from it, and cleaning up resources using the low-level smbprotocol API. ```python import uuid from smbprotocol.connection import Connection, Dialects from smbprotocol.session import Session from smbprotocol.tree import TreeConnect from smbprotocol.open import ( Open, ImpersonationLevel, FilePipePrinterAccessMask, CreateDisposition, CreateOptions, ShareAccess ) # Create connection guid = uuid.uuid4() conn = Connection(guid, "server") conn.connect() # Create session session = Session(conn, username="user", password="pass") session.connect() # Connect to tree (share) tree = TreeConnect(session, r"\\server\share") tree.connect() # Open file file = Open(tree, "folder\file.txt") file.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=FilePipePrinterAccessMask.FILE_READ_DATA, file_attributes=0, share_access=ShareAccess.FILE_SHARE_READ, create_disposition=CreateDisposition.FILE_OPEN, create_options=CreateOptions.FILE_NON_DIRECTORY_FILE ) # Read from file data = file.read(0, 1024) # Cleanup file.close() tree.disconnect() session.disconnect() conn.disconnect() ``` -------------------------------- ### Low-Level SMB Protocol Operations Example Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/03-connection-api.md Demonstrates establishing a connection, session, tree connect, and opening a file using the smbprotocol library. Ensure necessary imports are included. ```python import uuid from smbprotocol.connection import Connection, Dialects from smbprotocol.session import Session from smbprotocol.tree import TreeConnect from smbprotocol.open import Open, ImpersonationLevel, FilePipePrinterAccessMask, CreateDisposition, CreateOptions # Create connection guid = uuid.uuid4() conn = Connection(guid, "192.168.1.100") conn.connect() # Create session session = Session(conn, username="user", password="pass") session.connect() # Connect to tree tree = TreeConnect(session, r"\\192.168.1.100\share") tree.connect() # Open file file = Open(tree, "folder\file.txt") create_contexts = file.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=FilePipePrinterAccessMask.FILE_READ_DATA, file_attributes=0, share_access=1, # FILE_SHARE_READ create_disposition=CreateDisposition.FILE_OPEN, create_options=CreateOptions.FILE_NON_DIRECTORY_FILE ) # Use file... file.close() tree.disconnect() session.disconnect() conn.disconnect() ``` -------------------------------- ### Setup and Run Integration Tests Source: https://github.com/jborean93/smbprotocol/blob/master/tests/integration/README.md Commands to set up virtual machines, configure hosts with Ansible, and run integration tests. Ensure the 'artifact.zip' is present before running 'main.yml'. ```bash vagrant up ``` ```bash ansible-playbook main.yml -vv ``` ```bash ansible-playbook tests.yml -vv ``` -------------------------------- ### Perform SMB Operations with Credentials Source: https://github.com/jborean93/smbprotocol/blob/master/README.md Demonstrates creating a directory and writing to a file using smbclient. Credentials can be set globally via ClientConfig, registered per server, or provided directly to each function call. The example shows setting credentials globally and then using them for mkdir and open_file. ```python import smbclient # Optional - specify the default credentials to use on the global config object smbclient.ClientConfig(username='user', password='pass') # Optional - register the credentials with a server (overrides ClientConfig for that server) smbclient.register_session("server", username="user", password="pass") smbclient.mkdir(r"\\server\share\directory", username="user", password="pass") with smbclient.open_file(r"\\server\share\directory\file.txt", mode="w") as fd: fd.write(u"file contents") ``` -------------------------------- ### Import SMB Session Class Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Import the Session class from smbprotocol.session for handling authentication and session setup. ```python from smbprotocol.session import Session ``` -------------------------------- ### Client Configuration Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/MANIFEST.txt Documentation for the ClientConfig singleton, covering global configuration options, per-server registration, and DFS domain controller setup. ```APIDOC ## ClientConfig Singleton Documentation for the `ClientConfig` singleton, which manages global configuration options for the smbprotocol client. ### Global Configuration Options - Allows setting default parameters for client connections. ### Per-Server Registration - Enables configuring specific settings for individual SMB servers. ### DFS Domain Controller Setup - Provides guidance on configuring DFS domain controllers within the client configuration. ### Singleton Behavior - Explains the singleton pattern and provides examples of its usage. ``` -------------------------------- ### Connect to SMB Server Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/03-connection-api.md Establish a connection to the SMB server and negotiate protocol capabilities. A background thread is started for message processing. ```python from smbprotocol.connection import Dialects, Ciphers, SigningAlgorithms conn.connect() # Negotiate latest dialect # Force SMB 3.0.2 conn.connect(dialect=Dialects.SMB_3_0_2) # Specify preferred algorithms conn.connect( preferred_encryption_algos=[Ciphers.AES_256_GCM], preferred_signing_algos=[SigningAlgorithms.AES_GMAC] ) ``` -------------------------------- ### Create File and Get File ID Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/06-open-api.md Demonstrates creating a file and then printing its unique 16-byte file ID in hexadecimal format. ```python file.create(...) print(f"File ID: {file.file_id.hex()}") ``` -------------------------------- ### Handle SMBUnsupportedFeature Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/07-exceptions-and-errors.md Example of catching SMBUnsupportedFeature when attempting to enable encryption on an older SMB dialect. This demonstrates how to check the required and negotiated dialects. ```python from smbprotocol.exceptions import SMBUnsupportedFeature try: # Try to enable encryption on SMB 2.1 session = Session(conn, require_encryption=True) except SMBUnsupportedFeature as e: print(f"Error: {e.message}") print(f"Need dialect {e.required_dialect}, have {e.negotiated_dialect}") ``` -------------------------------- ### Get All File Information Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Fetches all available file metadata using a single query. The response is unpacked into a FileAllInformation object. ```python file_info = file.query_info(FileInformationClass.FileAllInformation) all_info = FileAllInformation() all_info.unpack(file_info['buffer'].get_value()) basic = all_info['basic_information'].get_value() standard = all_info['standard_information'].get_value() ``` -------------------------------- ### List Directory Contents with SMBClient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Use `listdir` to get a list of entry names within a directory. A `search_pattern` can be used to filter results. The returned names are not full paths. ```python def listdir(path: str, search_pattern: str = '*', **kwargs) -> list[str] ``` ```python entries = smbclient.listdir(r'\\server\share\folder') # Returns: ['file1.txt', 'file2.txt', 'subdir'] ``` -------------------------------- ### Using SMB Dialects with Connection Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/11-dialects-and-protocol-constants.md Demonstrates how to establish a connection using the latest supported SMB dialect or force a specific dialect. It also shows how to check the negotiated dialect after connection. ```python from smbprotocol.connection import Connection, Dialects # Use latest supported dialect (default) conn = Connection(guid, "server") conn.connect() # Force specific dialect conn = Connection(guid, "server") conn.connect(dialect=Dialects.SMB_3_0_2) # Check negotiated dialect if conn.dialect >= Dialects.SMB_3_1_1: print("Using SMB 3.1.1 or later") ``` -------------------------------- ### Get Volume Information (stat_volume) Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Retrieves volume statistics for an SMB share. Use this to get information about the total size and available space on a volume. ```python def stat_volume(path: str, **kwargs) -> SMBStatVolumeResult: # Returns volume statistics for the share. ``` -------------------------------- ### Get File Status (stat) Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Retrieves file metadata including permissions, size, and timestamps. Use this to get detailed information about a file, optionally following symbolic links. ```python def stat(path: str, follow_symlinks: bool = True, **kwargs) -> SMBStatResult: # Returns file metadata in a named tuple with extended SMB attributes. ``` ```python SMBStatResult = namedtuple('SMBStatResult', [ 'st_mode', 'st_ino', 'st_dev', 'st_nlink', 'st_uid', 'st_gid', 'st_size', 'st_atime', 'st_mtime', 'st_ctime', 'st_chgtime', 'st_atime_ns', 'st_mtime_ns', 'st_ctime_ns', 'st_chgtime_ns', 'st_file_attributes', 'st_reparse_tag', ]) ``` -------------------------------- ### query_directory Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/06-open-api.md Lists files within a directory, with options for filtering and starting point. ```APIDOC ## query_directory ### Description Lists files in a directory. ### Method Signature ```python def query_directory( file_information_class: int, file_index: int = 0, search_pattern: str = "*", restart_scan: bool = False ) -> list ``` ### Parameters #### Path Parameters - **file_information_class** (int) - Required - Information type (FileInformationClass) - **file_index** (int) - Optional - Starting index for enumeration (Default: 0) - **search_pattern** (str) - Optional - Wildcard pattern (Default: "*") - **restart_scan** (bool) - Optional - Restart enumeration if True (Default: False) ### Returns List of directory entries (structure varies by information class) ### Example ```python from smbprotocol.file_info import FileInformationClass directory.create(...) # Open for listing entries = directory.query_directory( file_information_class=FileInformationClass.FileDirectoryInformation, search_pattern="*.txt" ) ``` ``` -------------------------------- ### Create Directories Recursively with SMBClient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Use `makedirs` to create a directory and any necessary parent directories. Set `exist_ok=True` to prevent errors if the directory already exists. ```python def makedirs(path: str, exist_ok: bool = False, **kwargs) -> None ``` -------------------------------- ### getxattr Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Gets the value of an extended attribute for a file. Can optionally follow symbolic links. ```APIDOC ## getxattr ### Description Gets an extended attribute value. ### Method `getxattr(path: str, attribute: str, follow_symlinks: bool = True, **kwargs)` ### Parameters #### Path Parameters - **path** (str) - Required - File path - **attribute** (str) - Required - Attribute name #### Query Parameters - **follow_symlinks** (bool) - Optional - Follow symlinks to target (Default: True) #### Request Body - **kwargs** (dict) - Optional - Authentication and connection options ### Response #### Success Response - **bytes** - The value of the extended attribute. ``` -------------------------------- ### stat_volume Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Gets volume information for the specified share. This function returns statistics about the volume. ```APIDOC ## stat_volume ### Description Returns volume statistics for the share. ### Method `stat_volume(path: str, **kwargs)` ### Parameters #### Path Parameters - **path** (str) - Required - UNC path on the volume #### Request Body - **kwargs** (dict) - Optional - Authentication and connection options ### Response #### Success Response - **SMBStatVolumeResult** (tuple) - Tuple containing (total_size, caller_available_size, actual_available_size). ``` -------------------------------- ### Low-Level Protocol Control with smbprotocol Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/INDEX.md Illustrates the steps for establishing a connection, session, and tree connect to perform file operations at a low level. This involves explicit management of connection, session, and tree resources. ```python import uuid from smbprotocol.connection import Connection from smbprotocol.session import Session from smbprotocol.tree import TreeConnect from smbprotocol.open import Open, ImpersonationLevel, CreateDisposition guid = uuid.uuid4() conn = Connection(guid, "server") conn.connect() session = Session(conn, username="user", password="pass") session.connect() tree = TreeConnect(session, r"\\server\share") tree.connect() file = Open(tree, "file.txt") file.create(..., create_disposition=CreateDisposition.FILE_OPEN) data = file.read(0, 1024) file.close() tree.disconnect() session.disconnect() conn.disconnect() ``` -------------------------------- ### High-Level File Access with smbclient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/INDEX.md Demonstrates how to open a file and read its content using the high-level smbclient interface. Ensure ClientConfig is set up before use. ```python import smbclient smbclient.ClientConfig(username='user', password='pass') with smbclient.open_file(r'\\server\share\file.txt') as f: data = f.read() ``` -------------------------------- ### Handle SMBAuthenticationError Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/07-exceptions-and-errors.md Example of catching SMBAuthenticationError when connecting to a session. This demonstrates how to gracefully handle authentication failures. ```python from smbprotocol.exceptions import SMBAuthenticationError try: session.connect() except SMBAuthenticationError as e: print(f"Authentication failed: {e}") ``` -------------------------------- ### lstat Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Gets file status without following symbolic links. This is similar to `stat()` but specifically for the link itself. ```APIDOC ## lstat ### Description Gets file status without following symlinks. Same as `stat()` but does not follow symlinks. ### Method `lstat(path: str, **kwargs)` ### Parameters #### Path Parameters - **path** (str) - Required - UNC path to file #### Request Body - **kwargs** (dict) - Optional - Authentication and connection options ### Response #### Success Response - **SMBStatResult** (namedtuple) - Named tuple with file status and extended attributes. ``` -------------------------------- ### Open and Write/Read File with smbclient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Demonstrates how to open a file on a remote SMB share in write mode and then read from it. Ensure the server and share path are correct. ```python import smbclient # Write to a file with smbclient.open_file(r'\\server\share\file.txt', mode='w') as f: f.write('Hello, SMB!') # Read from a file with smbclient.open_file(r'\\server\share\file.txt', mode='r') as f: content = f.read() ``` -------------------------------- ### Get All File Metadata Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Retrieves all available metadata for a file using FileAllInformation. Imports FileInformationClass and FileAllInformation. ```python from smbprotocol.file_info import FileInformationClass, FileAllInformation file_info = file.query_info(FileInformationClass.FileAllInformation) all_info = FileAllInformation() all_info.unpack(file_info['buffer'].get_value()) # Access any substructure basic = all_info['basic_information'].get_value() standard = all_info['standard_information'].get_value() filename = all_info['name'].get_value() ``` -------------------------------- ### Open.create Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/06-open-api.md Opens or creates a file or directory on the SMB server with specified access rights, attributes, and options. ```APIDOC ## Open.create ### Description Opens or creates a file/directory on the server. ### Method POST ### Endpoint /tree/{tree_id}/share/{share_id}/file/{file_id} ### Parameters #### Path Parameters - **tree** (TreeConnect) - Required - TreeConnect object (share connection) - **name** (str) - Required - File/directory name relative to share root #### Query Parameters - **impersonation_level** (int) - Required - Impersonation level (ImpersonationLevel.Impersonation=2 typical) - **desired_access** (int) - Required - Access rights (FilePipePrinterAccessMask or DirectoryAccessMask) - **file_attributes** (int) - Required - File attributes to set (0 for defaults) - **share_access** (int) - Required - Share mode (ShareAccess.FILE_SHARE_READ, etc.) - **create_disposition** (int) - Required - Action if file exists (CreateDisposition) - **create_options** (int) - Required - Creation options (CreateOptions flags) - **create_contexts** (Optional[list]) - Optional - SMB2 create contexts for additional functionality - **oplock_level** (int) - Optional - Default: RequestedOplockLevel.SMB2_OPLOCK_LEVEL_NONE - Requested oplock level (RequestedOplockLevel) - **send** (bool) - Optional - Default: True - If False, returns (SMB2CreateRequest, receive_func) for out-of-band sending ### Response #### Success Response (200) - **create_contexts_response** (list) - list of create context responses (if any), or None ### Response Example ```json { "create_contexts_response": [] } ``` ### Example ```python from smbprotocol.open import CreateDisposition, CreateOptions, FilePipePrinterAccessMask, ShareAccess, ImpersonationLevel # Open existing file for reading file = Open(tree, "document.txt") file.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=FilePipePrinterAccessMask.FILE_READ_DATA, file_attributes=0, share_access=ShareAccess.FILE_SHARE_READ, create_disposition=CreateDisposition.FILE_OPEN, create_options=CreateOptions.FILE_NON_DIRECTORY_FILE ) # Create new file (overwrite if exists) file = Open(tree, "newfile.txt") file.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=FilePipePrinterAccessMask.FILE_WRITE_DATA | FilePipePrinterAccessMask.FILE_READ_DATA, file_attributes=0, share_access=0, create_disposition=CreateDisposition.FILE_OVERWRITE_IF, create_options=CreateOptions.FILE_NON_DIRECTORY_FILE ) # Open directory directory = Open(tree, "folder") directory.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=DirectoryAccessMask.FILE_LIST_DIRECTORY, file_attributes=0, share_access=ShareAccess.FILE_SHARE_READ, create_disposition=CreateDisposition.FILE_OPEN, create_options=CreateOptions.FILE_DIRECTORY_FILE ) ``` ``` -------------------------------- ### Configure Connection Signing Requirements Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/11-dialects-and-protocol-constants.md Demonstrates how to instantiate a Connection object with specific signing requirements. Set `require_signing=True` to enforce signing. ```python from smbprotocol.connection import Connection, SecurityMode # Require signing (default for most dialects) conn = Connection(guid, "server", require_signing=True) # Allow but not require signing conn = Connection(guid, "server", require_signing=False) ``` -------------------------------- ### Get File Size Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Retrieves the size of a file using FileStandardInformation. Requires importing FileInformationClass and FileStandardInformation. ```python from smbprotocol.file_info import FileInformationClass, FileStandardInformation file_info = file.query_info(FileInformationClass.FileStandardInformation) standard = FileStandardInformation() standard.unpack(file_info['buffer'].get_value()) size = standard['end_of_file'].get_value() print(f"File size: {size} bytes") ``` -------------------------------- ### Get the directory name of a path Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/10-path-utilities-and-dfs.md Use `dirname` to extract the directory portion from a given UNC path. ```python dirname = smbclient.path.dirname(r'\\server\share\folder\file.txt') # Returns: \\server\share\folder ``` -------------------------------- ### Create a Single Directory with SMBClient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Use `mkdir` to create a single directory. Ensure the parent directory exists, as it will raise `FileNotFoundError` if it does not. ```python def mkdir(path: str, **kwargs) -> None ``` -------------------------------- ### send Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/03-connection-api.md Sends a single SMB message to the server and returns immediately. Use `receive()` to get the response. ```APIDOC ## send ### Description Sends a single SMB message to the server and returns immediately. Use `receive()` to get the response. ### Method `send( message, sid: Optional[int] = None, tid: Optional[int] = None, credit_request: Optional[int] = None, message_id: Optional[int] = None, async_id: Optional[int] = None, force_signature: bool = False ) -> Request` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **message** (Structure) - Required - SMB message to send (e.g., SMB2CreateRequest) - **sid** (int) - Optional - Session ID for the message - **tid** (int) - Optional - Tree ID for the message - **credit_request** (int) - Optional - Additional SMB credits to request - **message_id** (int) - Optional - Explicit message ID (auto-assigned if None) - **async_id** (int) - Optional - Async ID for cancellation - **force_signature** (bool) - Optional - Force signing even if not required ### Request Example ```python from smbprotocol.open import SMB2CreateRequest create_req = SMB2CreateRequest() # ... populate create_req fields ... request = conn.send(create_req, sid=session_id, tid=tree_id) response_header = conn.receive(request) ``` ### Response #### Success Response (200) - **Request** - object to pass to `receive()` for getting response ``` -------------------------------- ### Global Client Configuration Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Sets up global client configuration for SMB operations, including authentication details, domain controller for DFS, DFS enablement, and authentication protocol. ```python import smbclient config = smbclient.ClientConfig( username='user', password='password', domain_controller='dc.example.com', # For DFS resolution skip_dfs=False, # Enable DFS auth_protocol='negotiate', # 'negotiate', 'ntlm', or 'kerberos' require_secure_negotiate=True, # Prevent downgrade attacks ) ``` -------------------------------- ### Handle SMBConnectionClosed Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/07-exceptions-and-errors.md Example of catching SMBConnectionClosed when reading data from a file. This shows how to react to an unexpected connection termination. ```python from smbprotocol.exceptions import SMBConnectionClosed try: data = file.read(0, 1024) except SMBConnectionClosed: print("Connection closed by server") ``` -------------------------------- ### stat Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Gets file status and metadata, including extended SMB attributes. It can optionally follow symbolic links. ```APIDOC ## stat ### Description Gets file metadata in a named tuple with extended SMB attributes. Can optionally follow symlinks. ### Method `stat(path: str, follow_symlinks: bool = True, **kwargs)` ### Parameters #### Path Parameters - **path** (str) - Required - UNC path to file #### Query Parameters - **follow_symlinks** (bool) - Optional - Follow symlinks to target (Default: True) #### Request Body - **kwargs** (dict) - Optional - Authentication and connection options ### Response #### Success Response - **SMBStatResult** (namedtuple) - Named tuple with file status and extended attributes. ``` -------------------------------- ### Connect to SMB Server Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/04-session-api.md Authenticates the session with the server using SMB SESSION_SETUP exchanges. Catches authentication or protocol errors. ```python session = Session(conn, username="user", password="pass") try: session.connect() except SMBAuthenticationError as e: print(f"Login failed: {e}") ``` -------------------------------- ### Get File Name Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/06-open-api.md Retrieves and prints the file name, which is the path relative to the share root and is read-only after creation. ```python print(f"File: {file.file_name}") ``` -------------------------------- ### Initialize ClientConfig Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/02-client-config.md Create or update the ClientConfig singleton with default or custom parameters. Subsequent instantiations update the existing singleton. ```python def __init__( self, client_guid: Optional[uuid.UUID] = None, username: Optional[str] = None, password: Optional[str] = None, domain_controller: Optional[str] = None, skip_dfs: bool = False, auth_protocol: str = "negotiate", require_secure_negotiate: bool = True, **kwargs ) -> None: ``` -------------------------------- ### Get Tree Connection Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/04-session-api.md Retrieves or creates a tree connection to a specified share. The share is identified by its UNC path. ```python tree = session.get_tree(r"\\server\share") ``` -------------------------------- ### connect Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/04-session-api.md Authenticates the session with the server by performing SMB SESSION_SETUP exchanges. After a successful connection, the session ID, session key are set, and the session is added to the connection's session table. ```APIDOC ## connect ### Description Authenticates the session with the server. Performs SMB SESSION_SETUP exchanges. ### Method ```python def connect(self) -> None ``` ### Raises - `SMBAuthenticationError` — Authentication failed - `SMBException` — Protocol error - `SMBResponseException` — Server returned error ### Example ```python session = Session(conn, username="user", password="pass") try: session.connect() except SMBAuthenticationError as e: print(f"Login failed: {e}") ``` ``` -------------------------------- ### Configure SMB Encryption Algorithms Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/11-dialects-and-protocol-constants.md Shows how to connect with default encryption algorithms or specify a preferred list. The server selects from the offered list based on its supported algorithms. ```python from smbprotocol.connection import Connection, Ciphers # Default: server picks from offered list conn.connect() # Specify preferred algorithms (highest to lowest priority) conn.connect( preferred_encryption_algos=[ Ciphers.AES_256_GCM, Ciphers.AES_128_GCM, Ciphers.AES_256_CCM, Ciphers.AES_128_CCM, ] ) ``` -------------------------------- ### Set Client GUID Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/02-client-config.md Assign a specific UUID to the client configuration. Defaults to a randomly generated UUID if not set. ```python config = ClientConfig() config.client_guid = uuid.UUID('12345678-1234-5678-1234-567812345678') ``` -------------------------------- ### Get Extended Attribute (getxattr) Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Retrieves the value of a specific extended attribute for a file. Optionally follow symbolic links. ```python def getxattr(path: str, attribute: str, follow_symlinks: bool = True, **kwargs) -> bytes: # Gets an extended attribute value. ``` -------------------------------- ### Read a File with smbclient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Configure client credentials globally and then open and read a file from an SMB share using smbclient. ```python import smbclient # Configure credentials globally smbclient.ClientConfig(username='user', password='pass') # Read file with smbclient.open_file(r'\\server\share\file.txt') as f: content = f.read() ``` -------------------------------- ### Get the base name of a path Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/10-path-utilities-and-dfs.md Use `basename` to extract the final component (file or directory name) from a UNC path. ```python filename = smbclient.path.basename(r'\\server\share\folder\file.txt') # Returns: file.txt ``` -------------------------------- ### Create and Write File with SMB Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/06-open-api.md Creates a new file and writes data to it, specifying write access and no sharing. Use this pattern for generating new files. ```python file = Open(tree, "newfile.txt") file.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=FilePipePrinterAccessMask.FILE_WRITE_DATA, file_attributes=0, share_access=0, create_disposition=CreateDisposition.FILE_CREATE, create_options=CreateOptions.FILE_NON_DIRECTORY_FILE ) file.write(0, b"Hello, SMB world!") file.close() ``` -------------------------------- ### Initialize FileFsFullSizeInformation Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Initializes a FileFsFullSizeInformation object to retrieve volume space details. Requires importing FileFsFullSizeInformation from smbprotocol.file_info. ```python from smbprotocol.file_info import FileFsFullSizeInformation size_info = FileFsFullSizeInformation() # Fields: # 'total_allocation_units' — Total blocks # 'available_allocation_units' — Free blocks # 'sectors_per_allocation_unit' — Block size in sectors # 'bytes_per_sector' — Sector size ``` -------------------------------- ### Get Share Name Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/05-tree-connect-api.md Prints the UNC path of the connected share. The share_name is read-only after the tree connect object is created. ```python print(f"Connected to: {tree.share_name}") ``` -------------------------------- ### Query and Set File Basic Information Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Demonstrates how to query basic file information and set the last write time. Requires importing datetime and specific file info classes. ```python import datetime from smbprotocol.file_info import FileBasicInformation, FileInformationClass # Get basic info file_info = file.query_info(FileInformationClass.FileBasicInformation) basic = FileBasicInformation() basic.unpack(file_info['buffer'].get_value()) attrs = basic['file_attributes'].get_value() # Set timestamps basic = FileBasicInformation() basic['last_write_time'] = int(datetime.datetime.now().timestamp() * 10_000_000 + 116444736000000000) file.set_info(FileInformationClass.FileBasicInformation, basic) ``` -------------------------------- ### Connect to a Tree using Session Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/04-session-api.md Demonstrates how to connect to an SMB share using the Session object. It shows both direct TreeConnect usage and the helper method get_tree. ```python session.connect() # Connect to a tree tree = TreeConnect(session, r"\\server\share") tree.connect() # Alternatively, using get_tree helper tree = session.get_tree(r"\\server\share") ``` -------------------------------- ### Get File Information with smbclient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Retrieve file metadata, such as size and modification time, for a file on an SMB share using smbclient. ```python import smbclient stat = smbclient.stat(r'\\server\share\file.txt') print(f'Size: {stat.st_size} bytes') print(f'Modified: {stat.st_mtime}') ``` -------------------------------- ### Import Connection and Dialects Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/03-connection-api.md Import the necessary classes for establishing an SMB connection. ```python from smbprotocol.connection import Connection, Dialects ``` -------------------------------- ### Configure SMB Signing Algorithms Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/11-dialects-and-protocol-constants.md Connects to a server using preferred signing algorithms in a specified priority order. The server will use the highest priority algorithm supported by both client and server. ```python from smbprotocol.connection import Connection, SigningAlgorithms # Use preferred algorithms in priority order conn.connect( preferred_signing_algos=[ SigningAlgorithms.AES_GMAC, SigningAlgorithms.AES_CMAC, SigningAlgorithms.HMAC_SHA256, ] ) ``` -------------------------------- ### Open and Create a File Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/05-tree-connect-api.md Opens or creates a file on a connected tree with specified access rights and creation options. Ensure the tree is connected before opening a file and always close the file and disconnect the tree afterwards. ```python from smbprotocol.open import Open, ImpersonationLevel, FilePipePrinterAccessMask, CreateDisposition, CreateOptions tree.connect() file = Open(tree, "path/to/file.txt") create_contexts = file.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=FilePipePrinterAccessMask.FILE_READ_DATA, file_attributes=0, share_access=1, create_disposition=CreateDisposition.FILE_OPEN, create_options=CreateOptions.FILE_NON_DIRECTORY_FILE ) # Use file... file.close() tree.disconnect() ``` -------------------------------- ### Connect and Get Session ID Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/04-session-api.md Connect to the SMB server and retrieve the assigned session ID. The session ID is populated after a successful connection. ```python session.connect() print(f"Session ID: {hex(session.session_id)}") ``` -------------------------------- ### Import ClientConfig Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/02-client-config.md Import the ClientConfig class from the smbclient library. ```python from smbclient import ClientConfig ``` -------------------------------- ### Get File Standard Information Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Retrieves file size, allocation size, and whether the entry is a directory. Unpacks the buffer into a FileStandardInformation object. ```python file_info = file.query_info(FileInformationClass.FileStandardInformation) standard = FileStandardInformation() standard.unpack(file_info['buffer'].get_value()) size = standard['end_of_file'].get_value() alloc = standard['allocation_size'].get_value() is_dir = standard['directory'].get_value() print(f"Size: {size}, Allocated: {alloc}, Directory: {is_dir}") ``` -------------------------------- ### Get Alternate Data Streams Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Retrieves information about alternate data streams associated with a file. Iterates through the 'streams' field to print stream details. ```python file_info = file.query_info(FileInformationClass.FileStreamInformation) stream_info = FileStreamInformation() stream_info.unpack(file_info['buffer'].get_value()) streams = stream_info['streams'].get_value() for stream in streams: name = stream['stream_name'].get_value() size = stream['stream_size'].get_value() print(f"Stream: {name}, Size: {size}") ``` -------------------------------- ### Run Basic Tests Source: https://github.com/jborean93/smbprotocol/blob/master/README.md Executes the basic tests for the smbprotocol library with coverage reporting. ```bash python -m pytest -v --cov smbprotocol --cov-report term-missing ``` -------------------------------- ### Retry on Transient SMBConnectionClosed Errors Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/07-exceptions-and-errors.md Implement a retry mechanism for transient errors like SMBConnectionClosed. This example retries up to 3 times with a 1-second delay between attempts. ```python import time from smbprotocol.exceptions import SMBConnectionClosed for attempt in range(3): try: data = file.read(offset, size) break except SMBConnectionClosed: if attempt < 2: print(f"Connection lost, retrying...") time.sleep(1) else: raise ``` -------------------------------- ### Get Directory Size on SMB Share Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Calculates the total size of all files within a directory on an SMB share by walking through the directory structure. Requires smbclient. ```python import smbclient def get_dir_size(path): total = 0 for dirpath, dirnames, filenames in smbclient.walk(path): for filename in filenames: filepath = f'{dirpath}\\{filename}' stat = smbclient.stat(filepath) total += stat.st_size return total size = get_dir_size(r'\\server\share\folder') print(f'Total size: {size} bytes') ``` -------------------------------- ### Import File Basic Information Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Import FileBasicInformation from smbprotocol.file_info to retrieve basic file metadata. ```python from smbprotocol.file_info import FileBasicInformation ``` -------------------------------- ### Import smbclient.path utilities Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/10-path-utilities-and-dfs.md Import specific path functions or the entire module for use. ```python import smbclient.path ``` ```python from smbclient.path import exists, isdir, isfile, islink, join, dirname, basename ``` -------------------------------- ### Get File Status Without Following Symlinks (lstat) Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/01-smbclient-overview.md Retrieves file metadata without resolving symbolic links. Use this when you need information about the symlink itself, not its target. ```python def lstat(path: str, **kwargs) -> SMBStatResult: # Same as stat() but does not follow symlinks. ``` -------------------------------- ### Get Reparse Point Data Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/09-ioctl-and-advanced-operations.md Reads reparse point data from a file using FSCTL_GET_REPARSE_POINT. Ensure the file_id and connection details (session_id, tree_id) are correctly set. ```python from smbprotocol.ioctl import CtlCode, IOCTLFlags, SMB2IOCTLRequest, SMB2IOCTLResponse from smbprotocol.reparse_point import ReparseDataBuffer ioctl_req = SMB2IOCTLRequest() ioctl_req["ctl_code"] = CtlCode.FSCTL_GET_REPARSE_POINT ioctl_req["file_id"] = symlink_file.file_id ioctl_req["flags"] = IOCTLFlags.SMB2_0_IOCTL_IS_FSCTL ioctl_req["max_output_response"] = 4096 request = conn.send(ioctl_req, sid=session_id, tid=tree_id) response = conn.receive(request) ioctl_resp = SMB2IOCTLResponse() ioctl_resp.unpack(response["data"].get_value()) reparse_data = ReparseDataBuffer() reparse_data.unpack(ioctl_resp["buffer"].get_value()) reparse_tag = reparse_data["reparse_tag"].get_value() print(f"Reparse tag: 0x{reparse_tag:08x}") ``` -------------------------------- ### Get Tree Connect ID Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/05-tree-connect-api.md Retrieves and prints the server-assigned tree ID after establishing a connection. The tree_connect_id is initially None and populated upon calling the connect() method. ```python tree.connect() print(f"Tree ID: {hex(tree.tree_connect_id)}") ``` -------------------------------- ### Open and Read File with SMB Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/06-open-api.md Opens an existing file for reading, specifying desired access and share permissions. Ensure the file exists before attempting to open. ```python file = Open(tree, "document.txt") file.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=FilePipePrinterAccessMask.FILE_READ_DATA, file_attributes=0, share_access=ShareAccess.FILE_SHARE_READ, create_disposition=CreateDisposition.FILE_OPEN, create_options=CreateOptions.FILE_NON_DIRECTORY_FILE ) data = file.read(0, 4096) file.close() ``` -------------------------------- ### Write a File with smbclient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Open a file in write mode on an SMB share and write content to it using smbclient. ```python import smbclient with smbclient.open_file(r'\\server\share\newfile.txt', mode='w') as f: f.write('Hello, SMB!') ``` -------------------------------- ### Connect to SMB Server with Encryption Preference Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/11-dialects-and-protocol-constants.md Establishes a connection to an SMB server, specifying the dialect and preferred encryption algorithms. Use this to enforce specific security settings like AES-256-GCM. ```python from smbprotocol.connection import Connection, Dialects, Ciphers conn = Connection(guid, "server") conn.connect( dialect=Dialects.SMB_3_1_1, preferred_encryption_algos=[Ciphers.AES_256_GCM] # Force 256-bit ) ``` -------------------------------- ### Create Directories with smbclient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Create a new directory or a nested directory structure on an SMB share using smbclient's mkdir and makedirs functions. ```python import smbclient smbclient.mkdir(r'\\server\share\newfolder') smbclient.makedirs(r'\\server\share\path\to\deep\folder') ``` -------------------------------- ### Open and Read File (High-Level API) Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/README.md Opens a file on a remote SMB share and reads its content. Ensure smbclient.ClientConfig is configured with credentials. ```python import smbclient # Configure credentials smbclient.ClientConfig(username='user', password='pass') # Read file with smbclient.open_file(r'\\server\share\file.txt') as f: data = f.read() ``` -------------------------------- ### Import SMB Open Class Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Import the Open class from smbprotocol.open for performing file open operations. ```python from smbprotocol.open import Open ``` -------------------------------- ### Handle SMBOSError with errno mapping Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/07-exceptions-and-errors.md Example of catching SMBOSError and checking the errno attribute to determine the specific OS-level error, such as file not found or permission denied. It also prints the original NTSTATUS code. ```python from smbprotocol.exceptions import SMBOSError import errno try: smbclient.remove(r'\\server\share\file.txt') except SMBOSError as e: if e.errno == errno.ENOENT: print("File not found") elif e.errno == errno.EACCES: print("Permission denied") print(f"NtStatus: 0x{e.ntstatus:08x}") ``` -------------------------------- ### CreateOptions Constants Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/11-dialects-and-protocol-constants.md Defines various file opening options and flags, including file type, I/O behavior (write-through, sequential, buffering), special handling (delete on close, oplocks), and advanced options like opening by file ID or for backup. ```python from smbprotocol.open import CreateOptions class CreateOptions: # Basic type FILE_DIRECTORY_FILE = 0x00000001 # This is a directory FILE_NON_DIRECTORY_FILE = 0x00000040 # This is a regular file # I/O options FILE_WRITE_THROUGH = 0x00000002 # Write immediately to disk FILE_SEQUENTIAL_ONLY = 0x00000004 # Sequential access only FILE_NO_INTERMEDIATE_BUFFERING = 0x00000008 # Unbuffered I/O FILE_SYNCHRONOUS_IO_ALERT = 0x00000010 # Synchronous I/O FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020 # Synchronous I/O (non-alertable) # Special handling FILE_DELETE_ON_CLOSE = 0x00001000 # Delete file when closed FILE_COMPLETE_IF_OPLOCKED = 0x00000100 # Complete with oplock FILE_NO_EA_KNOWLEDGE = 0x00000200 # Don't process EAs FILE_RANDOM_ACCESS = 0x00000800 # Random access pattern # Advanced options FILE_OPEN_BY_FILE_ID = 0x00002000 # Open by file ID not name FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000 # Backup/restore access FILE_NO_COMPRESSION = 0x00008000 # Don't auto-decompress FILE_OPEN_REPARSE_POINT = 0x00200000 # Don't follow symlinks FILE_OPEN_NO_RECALL = 0x00400000 # Don't recall offline files FILE_OPEN_FOR_FREE_SPACE_QUERY = 0x00800000 # Free space query ``` -------------------------------- ### Send an SMB Message Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/03-connection-api.md Use this method to send a single SMB message to the server. The method returns immediately, and you must use `receive()` to get the response. It supports specifying session and tree IDs, requesting additional credits, and forcing message signing. ```python from smbprotocol.open import SMB2CreateRequest create_req = SMB2CreateRequest() # ... populate create_req fields ... request = conn.send(create_req, sid=session_id, tid=tree_id) response_header = conn.receive(request) ``` -------------------------------- ### Import TreeConnect and Session Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/05-tree-connect-api.md Import the necessary classes for creating and managing SMB share connections. ```python from smbprotocol.tree import TreeConnect from smbprotocol.session import Session ``` -------------------------------- ### Open Directory Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/06-open-api.md Opens an existing directory to list its contents. Ensure the path is a directory and the share has read permissions. ```python from smbprotocol.open import CreateDisposition, CreateOptions, DirectoryAccessMask, ShareAccess, ImpersonationLevel # Open directory directory = Open(tree, "folder") directory.create( impersonation_level=ImpersonationLevel.Impersonation, desired_access=DirectoryAccessMask.FILE_LIST_DIRECTORY, file_attributes=0, share_access=ShareAccess.FILE_SHARE_READ, create_disposition=CreateDisposition.FILE_OPEN, create_options=CreateOptions.FILE_DIRECTORY_FILE ) ``` -------------------------------- ### Initialize FileFsVolumeInformation Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/08-file-information-types.md Initializes a FileFsVolumeInformation object to retrieve volume name and serial number. Requires importing FileFsVolumeInformation from smbprotocol.file_info. ```python from smbprotocol.file_info import FileFsVolumeInformation vol_info = FileFsVolumeInformation() # Fields: volume_label, volume_serial_number ``` -------------------------------- ### List Files Matching Pattern on SMB Share Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Lists files in an SMB directory that match a specified search pattern. Ensure smbclient is imported. ```python import smbclient files = smbclient.listdir(r'\\server\share\folder', search_pattern='*.txt') for filename in files: print(filename) ``` -------------------------------- ### Import SMB Connection Class Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Import the Connection class from smbprotocol.connection for managing low-level network connections. ```python from smbprotocol.connection import Connection ``` -------------------------------- ### Import Session and Connection Classes Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/04-session-api.md Imports the necessary Session and Connection classes from the smbprotocol library. ```python from smbprotocol.session import Session from smbprotocol.connection import Connection ``` -------------------------------- ### Connection Constructor Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/03-connection-api.md Creates an SMB connection object. The network connection is not established until connect() is called. ```APIDOC ## Connection Constructor ### Description Creates an SMB connection object (does not establish network connection until `connect()` is called). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | guid | uuid.UUID | Yes | — | Unique client identifier sent to server | | server_name | str | Yes | — | Hostname or IP address of SMB server | | port | int | No | 445 | TCP port for SMB connection | | require_signing | bool | No | True | Whether message signing is mandatory | ### Request Example ```python import uuid from smbprotocol.connection import Connection guid = uuid.uuid4() conn = Connection(guid, "server.example.com", port=445) ``` ``` -------------------------------- ### Walk Directory Tree with smbclient Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/00-quick-reference.md Recursively traverse a directory tree on an SMB share, yielding directory paths, subdirectories, and filenames at each level using smbclient. ```python import smbclient for dirpath, dirnames, filenames in smbclient.walk(r'\\server\share'): print(f'Directory: {dirpath}') print(f'Subdirs: {dirnames}') print(f'Files: {filenames}') ``` -------------------------------- ### Initialize Connection Object Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/03-connection-api.md Create an instance of the Connection class. Network connection is not established until connect() is called. ```python import uuid from smbprotocol.connection import Connection guid = uuid.uuid4() conn = Connection(guid, "server.example.com", port=445) ``` -------------------------------- ### Connect to SMB Share Source: https://github.com/jborean93/smbprotocol/blob/master/_autodocs/05-tree-connect-api.md Establishes the tree connection to the share by performing the SMB TREE_CONNECT exchange. Handles potential network errors like share not found or access denied. After a successful connection, the tree_connect_id is set and the tree is added to the session's tree_connect_table. ```python tree = TreeConnect(session, r"\\server\share") try: tree.connect() except BadNetworkName: print("Share not found") except AccessDenied: print("Access denied to share") # After connect, tree.tree_connect_id is set print(f"Connected to tree ID: {hex(tree.tree_connect_id)}") ```