> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/fortra/impacket/llms.txt
> Use this file to discover all available pages before exploring further.

# Quick Start

> Get started with Impacket by building your first network protocol script

## Your First Impacket Script

This guide walks you through creating a simple script that connects to a remote SMB server and lists available shares.

<Steps>
  <Step title="Import Impacket">
    Start by importing the necessary modules:

    ```python theme={null}
    from impacket.smbconnection import SMBConnection
    from impacket.examples import logger
    import logging
    ```
  </Step>

  <Step title="Create an SMB Connection">
    Establish a connection to the target server:

    ```python theme={null}
    # Initialize connection
    server_name = "192.168.1.100"
    server_ip = "192.168.1.100"

    # Create SMBConnection instance
    smbConn = SMBConnection(server_name, server_ip, sess_port=445)
    ```

    <Note>
      The `sess_port` parameter defaults to 445 (SMB over TCP). Use 139 for SMB over NetBIOS.
    </Note>
  </Step>

  <Step title="Authenticate">
    Log in with credentials:

    ```python theme={null}
    username = "admin"
    password = "password123"
    domain = "WORKGROUP"

    # Login with username and password
    smbConn.login(username, password, domain)
    ```
  </Step>

  <Step title="Interact with SMB">
    Once authenticated, you can interact with the server:

    ```python theme={null}
    # List available shares
    shares = smbConn.listShares()

    for share in shares:
        print(f"Share: {share['shi1_netname'][:-1]}")
        print(f"  Type: {share['shi1_type']}")
        print(f"  Comment: {share['shi1_remark'][:-1]}")
    ```
  </Step>

  <Step title="Clean Up">
    Always close the connection when done:

    ```python theme={null}
    smbConn.logoff()
    ```
  </Step>
</Steps>

## Complete Example

Here's a complete working example that lists SMB shares:

```python smb_list_shares.py theme={null}
from impacket.smbconnection import SMBConnection
import sys
import logging

def list_shares(target_ip, username, password, domain=''):
    """
    Connect to an SMB server and list available shares.
    
    Args:
        target_ip: IP address of the target server
        username: Username for authentication
        password: Password for authentication
        domain: Domain name (optional)
    """
    try:
        # Create connection
        smbConn = SMBConnection(target_ip, target_ip, sess_port=445)
        
        # Authenticate
        smbConn.login(username, password, domain)
        print(f"[+] Successfully authenticated to {target_ip}")
        
        # List shares
        print("\n[*] Available shares:")
        shares = smbConn.listShares()
        
        for share in shares:
            share_name = share['shi1_netname'][:-1]
            share_type = share['shi1_type']
            share_comment = share['shi1_remark'][:-1]
            
            print(f"\n  Share: {share_name}")
            print(f"    Type: {share_type}")
            print(f"    Comment: {share_comment}")
        
        # Clean up
        smbConn.logoff()
        print("\n[+] Connection closed")
        
    except Exception as e:
        print(f"[!] Error: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print(f"Usage: {sys.argv[0]} <target_ip> <username> <password>")
        sys.exit(1)
    
    target = sys.argv[1]
    user = sys.argv[2]
    passwd = sys.argv[3]
    
    list_shares(target, user, passwd)
```

### Running the Example

```bash theme={null}
python smb_list_shares.py 192.168.1.100 admin password123
```

## Authentication Methods

Impacket supports multiple authentication methods:

<Tabs>
  <Tab title="Password">
    Standard password authentication:

    ```python theme={null}
    smbConn.login(username, password, domain)
    ```
  </Tab>

  <Tab title="NTLM Hash">
    Authenticate using NTLM hashes (pass-the-hash):

    ```python theme={null}
    lm_hash = "aad3b435b51404eeaad3b435b51404ee"
    nt_hash = "8846f7eaee8fb117ad06bdd830b7586c"

    smbConn.login(username, '', domain, lm_hash, nt_hash)
    ```

    <Note>
      Leave the password field empty when using hashes.
    </Note>
  </Tab>

  <Tab title="Kerberos">
    Use Kerberos authentication:

    ```python theme={null}
    # Enable Kerberos
    smbConn.kerberosLogin(
        username, 
        password, 
        domain, 
        lmhash='', 
        nthash='', 
        aesKey='',  # Optional AES key
        kdcHost='dc.domain.com'  # Domain controller
    )
    ```
  </Tab>
</Tabs>

## Working with DCERPC

Impacket provides powerful DCERPC capabilities. Here's an example using the DCERPCTransportFactory:

```python detect_architecture.py theme={null}
from impacket.dcerpc.v5.transport import DCERPCTransportFactory
from impacket.dcerpc.v5.epm import MSRPC_UUID_PORTMAP
from impacket.dcerpc.v5.rpcrt import DCERPCException

def detect_architecture(target_ip):
    """
    Detect if target system is 32-bit or 64-bit.
    Based on getArch.py example.
    """
    NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0')
    
    try:
        # Create transport
        stringBinding = f'ncacn_ip_tcp:{target_ip}[135]'
        transport = DCERPCTransportFactory(stringBinding)
        transport.set_connect_timeout(5)
        
        # Connect and bind
        dce = transport.get_dce_rpc()
        dce.connect()
        
        try:
            dce.bind(MSRPC_UUID_PORTMAP, transfer_syntax=NDR64Syntax)
            print(f"{target_ip} is 64-bit")
        except DCERPCException as e:
            if 'syntaxes_not_supported' in str(e):
                print(f"{target_ip} is 32-bit")
            else:
                raise
        
        dce.disconnect()
        
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    detect_architecture("192.168.1.100")
```

## Common Patterns

### Error Handling

Always implement proper error handling:

```python theme={null}
from impacket.smbconnection import SessionError

try:
    smbConn = SMBConnection(target, target_ip)
    smbConn.login(username, password, domain)
    # Your code here
except SessionError as e:
    print(f"SMB Session Error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
finally:
    if smbConn:
        smbConn.logoff()
```

### Using the Examples Logger

Impacket includes a logger utility for consistent output:

```python theme={null}
from impacket.examples import logger
import logging

# Initialize logger with timestamp and debug options
logger.init(ts=True, debug=True)

# Use logging
logging.info("Connection established")
logging.error("Failed to authenticate")
logging.debug("Detailed debug information")
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="/authentication/overview">
    Learn about NTLM, Kerberos, and credential formats
  </Card>

  <Card title="SMB Protocol" icon="network-wired" href="/protocols/smb">
    Dive deeper into SMB/CIFS functionality
  </Card>

  <Card title="MS-RPC" icon="code" href="/protocols/msrpc">
    Explore MSRPC and DCERPC capabilities
  </Card>

  <Card title="Examples" icon="lightbulb" href="/examples">
    Browse complete example scripts and use cases
  </Card>
</CardGroup>

<Warning>
  Always ensure you have proper authorization before connecting to remote systems. Unauthorized access is illegal.
</Warning>
