On this page
netrc
Prev: multiprocessing | Up: stdlib_module | Next: nt
Rel: csv, configparser, tomllib, plistlib
Ref: docs.python.org โ netrc
Tags: #public #python3 #stdlib
Import
import netrc
Overview
Parser for Unix .netrc configuration files (machine, login, account, password, default). Use netrc when writing CLI tools or HTTP/FTP clients that honor a user's existing .netrc entries instead of prompting interactively or hardcoding configuration values.
Quick Start
import netrc
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
rc = Path(tmp) / "sample_netrc"
rc.write_text("machine api.example.com login demo_user password demo_val\n", encoding="utf-8")
rc.chmod(0o600)
auth = netrc.netrc(rc).authenticators("api.example.com")
assert auth == ("demo_user", None, "demo_val")
Implementation Walkthrough
1. Graceful Fallback When .netrc Is Missing
Wrap netrc.netrc() to handle missing files or permission errors cleanly before falling back to environment variables or getpass:
import netrc
def lookup_creds(host: str) -> tuple[str, str] | None:
try:
auth = netrc.netrc().authenticators(host)
except (FileNotFoundError, netrc.NetrcParseError):
return None
if auth is None:
return None
login, _account, value = auth
return (login, value)
Gotchas & Boundaries
- Strict file permissions on Unix:
netrc.netrc()raisesNetrcParseErrorif the default.netrcfile in the user's home directory is readable by group or others (owner-only0600permissions are required). - Plaintext storage:
.netrcfiles are stored in plaintext on disk. For desktop apps or high-security workflows, prefer OS keychains (e.g.,keyring) or short-lived OAuth tokens. defaultfallback entry: If a.netrcfile contains adefaultstanza,authenticators(unknown_host)returns those values instead ofNone.
Classes & Objects
- netrc.netrc โ
netrc.netrcclass. (Methods:.authenticators()) - netrc.NetrcParseError โ Exception raised on syntax errors in the .netrc file. (Methods:
.add_note(),.with_traceback())
Linked from
Related notes
- tuts/python3/stdlib_module/configparser Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/csv Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/nt Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/plistlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tomllib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/getpass Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/netrc/netrc Linked here; shared tags: #stdlib