pysmb

1.2.13 · active · verified Fri Apr 10

pysmb is an experimental SMB/CIFS library written in Python that provides a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2). It enables Python applications to access and transfer files to and from SMB/CIFS shared folders, such as Windows file shares and Samba folders. The library is actively maintained, with the current version 1.2.13 released on September 19, 2025, and regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SMB connection, optionally list shares, and retrieve a file from a remote SMB/CIFS server using the `SMBConnection` class. It uses environment variables for sensitive connection details to keep the code runnable without hardcoding credentials.

import os
import tempfile
from smb.SMBConnection import SMBConnection

# Replace with your SMB server details and credentials
SERVER_IP = os.environ.get('SMB_SERVER_IP', '127.0.0.1')
SERVER_NAME = os.environ.get('SMB_SERVER_NAME', 'MYSERVER') # Must match remote machine name
USER_ID = os.environ.get('SMB_USER_ID', 'guest')
PASSWORD = os.environ.get('SMB_PASSWORD', '')
CLIENT_MACHINE_NAME = os.environ.get('SMB_CLIENT_NAME', 'myclient') # Can be arbitrary
SHARE_NAME = os.environ.get('SMB_SHARE_NAME', 'public') # Example share name
REMOTE_FILE_PATH = os.environ.get('SMB_REMOTE_FILE_PATH', '/test.txt') # Path on the share

try:
    conn = SMBConnection(USER_ID, PASSWORD, CLIENT_MACHINE_NAME, SERVER_NAME, use_ntlm_v2=True)
    # Connect to the SMB server on port 445 (direct TCP) or 139 (NetBIOS session service)
    connected = conn.connect(SERVER_IP, 445)

    if connected:
        print(f"Successfully connected to {SERVER_IP} with user {USER_ID}")

        # Example: List shares (optional, sometimes IPC$ connection errors can occur)
        try:
            shares = conn.listShares()
            print("Available shares:")
            for share in shares:
                print(f"  - {share.name}")
        except Exception as e:
            print(f"Warning: Could not list shares (this might be expected for some configurations): {e}")

        # Example: Retrieve a file
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            file_attributes, filesize = conn.retrieveFile(SHARE_NAME, REMOTE_FILE_PATH, temp_file)
            print(f"Retrieved file '{REMOTE_FILE_PATH}' from share '{SHARE_NAME}'. Size: {filesize} bytes.")
            print(f"Local copy saved to: {temp_file.name}")

        # Always close the connection
        conn.close()
        print("Connection closed.")
    else:
        print(f"Failed to connect to {SERVER_IP}")

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →