requests-ntlm2: NTLM Authentication for Requests

6.6.0 · active · verified Thu Apr 16

requests-ntlm2 is a Python library that provides HTTP NTLM authentication support for the popular `requests` library. It is a fork of `requests-ntlm`, offering extended functionality, especially for NTLM proxy and server authentication. Currently at version 6.6.0, the library is actively maintained with regular updates to support modern Python environments and security protocols.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic NTLM authentication with `requests-ntlm2` using `HttpNtlmAuth`. It also shows the recommended approach of using it with a `requests.Session` for improved efficiency and connection pooling. Replace placeholder environment variables with your actual NTLM credentials and target URL.

import requests
from requests_ntlm2 import HttpNtlmAuth
import os

# Replace with your NTLM domain, username, and password
NTLM_USERNAME = os.environ.get('NTLM_USERNAME', 'DOMAIN\\username')
NTLM_PASSWORD = os.environ.get('NTLM_PASSWORD', 'password')
TARGET_URL = os.environ.get('TARGET_URL', 'http://ntlm_protected_site.com')

# Basic NTLM authentication
try:
    auth = HttpNtlmAuth(NTLM_USERNAME, NTLM_PASSWORD)
    response = requests.get(TARGET_URL, auth=auth)
    response.raise_for_status() # Raise an exception for bad status codes
    print(f"Successfully authenticated to {TARGET_URL}. Status: {response.status_code}")
    # print(response.text[:200]) # Print first 200 characters of content
except requests.exceptions.RequestException as e:
    print(f"Error during basic NTLM authentication: {e}")

# Using with a Session for efficiency (recommended for multiple requests)
from requests import Session
session = Session()
session.auth = HttpNtlmAuth(NTLM_USERNAME, NTLM_PASSWORD)

try:
    session_response = session.get(TARGET_URL)
    session_response.raise_for_status()
    print(f"Successfully authenticated with session to {TARGET_URL}. Status: {session_response.status_code}")
except requests.exceptions.RequestException as e:
    print(f"Error during session NTLM authentication: {e}")

view raw JSON →