Python library for managing hosts file (eg. /etc/hosts) in a Pythonic way:
- Platform independent (Linux, macOS, Windows)
- Uses immutable Python dataclasses to represent hosts entries
- Modern, type-safe API with full type hints
- Implements MutableSequence protocol for list-like operations
from pyhosts import Hosts
# Load the system hosts file
myhosts = Hosts()
# Iterate over all host entries
for host in myhosts:
print(host)
# Host(ip_address=IPv4Address('127.0.0.1'), hostname='localhost', aliases=('localhost.localdomain',), comment=None)
# Host(ip_address=IPv6Address('::1'), hostname='localhost6', aliases=('localhost6.localdomain6',), comment=None)# Access hosts by hostname (attribute-style)
host = myhosts.localhost
print(host.ip_address) # IPv4Address('127.0.0.1')
print(host.hostname) # 'localhost'
print(host.aliases) # ('localhost.localdomain',)
print(host.comment) # None
# Access by index (list-style)
first_host = myhosts[0]
# Check if a host exists
if 'localhost' in myhosts:
print("localhost entry found")# Find all hosts matching a query (by IP, hostname, or alias)
results = myhosts.find('192.168.1.1')
results = myhosts.find('localhost')
# Find the first matching host
host = myhosts.find_one('localhost')from pyhosts import Host
from ipaddress import ip_address
# Create a new host entry
new_host = Host(
ip_address=ip_address('192.168.1.100'),
hostname='myserver',
aliases=('server', 'web'),
comment='Production server'
)
# Add the host
myhosts.add(new_host)
# Remove hosts by query (returns count of removed entries)
count = myhosts.remove('myserver')
print(f"Removed {count} host(s)")# Save changes back to the hosts file
myhosts.save()
# Save without header comment
myhosts.save(write_header=False)
# Save with backup
myhosts.save(backup=True)- Python 3.10 or higher
- No external dependencies (uses standard library only)
pip install pyhostsOr install from source:
git clone https://github.com/igormilovanovic/pyhosts.git
cd pyhosts
pip install -e .# Install development dependencies
pip install -r test-requirements.txt
# Run tests
pytest test/
# Run with coverage
pytest test/ --cov=pyhosts# Check code style (max line length: 120)
pycodestyle pyhosts/ --max-line-length=120pyhosts/hosts.py- MainHostsclass for managing hosts filepyhosts/models.py-Hostdataclass representing individual entriespyhosts/parser.py- Parsing and writing hosts file contentpyhosts/platform_resolver.py- Platform-specific hosts file location
The main class for managing the hosts file.
Methods:
load()- Load entries from hosts filesave(backup=False, write_header=True)- Save entries to hosts filefind(query: str)- Find all hosts matching query (IP, hostname, or alias)find_one(query: str)- Find first host matching queryadd(host: Host, allow_duplicates=False)- Add a new host entryremove(query: str)- Remove all hosts matching query- Supports list operations: indexing, slicing, iteration,
len(),inoperator
Immutable dataclass representing a single host entry.
Attributes:
ip_address- IPv4Address or IPv6Addresshostname- Primary hostname (str)aliases- Tuple of alias namescomment- Optional inline comment (str)
Methods:
from_line(line: str)- Parse a line from hosts fileto_line()- Format as hosts file linematches(query: str)- Check if entry matches queryall_names- Property returning all names (hostname + aliases)
DuplicateEntryError- Raised when adding duplicate host entryPlatformNotSupportedError- Raised on unsupported platform