How to Write an IP Block List to hosts.deny in Python
This Python script validates a list of IP addresses and CIDR ranges, then writes them to a hosts.deny file to block connections at the TCP wrapper level.
Python code
15 linesfrom ipaddress import ip_network
def write_hosts_deny(ip_list, output_file="hosts.deny"):
with open(output_file, "w") as f:
for ip in ip_list:
try:
ip_network(ip)
f.write(f"ALL: {ip}\n")
except ValueError:
continue
print(f"Written {len(ip_list)} entries to {output_file}")
if __name__ == "__main__":
blocked_ips = ["192.168.1.1", "10.0.0.0/8", "not-an-ip", "172.16.5.5"]
write_hosts_deny(blocked_ips)
Output
Written 4 entries to hosts.deny
hosts.deny contents:
ALL: 192.168.1.1
ALL: 10.0.0.0/8
ALL: 172.16.5.5
How it works
The ip_network function from the ipaddress module validates each IP or CIDR string. If parsing succeeds, the entry is written; otherwise a ValueError is raised and the invalid entry is silently skipped. Using a context manager (with open(...)) guarantees the file is closed properly even if an exception occurs. Writing ALL: <ip> follows the standard hosts.deny syntax that the TCP wrapper library understands.
Common mistakes
- Not filtering invalid IPs before writing, which corrupts the hosts.deny file
- Forgetting that `ip_network` accepts CIDR ranges like '10.0.0.0/8', so simple string checks are insufficient
- Overwriting the file with `"w"` instead of appending with `"a"`, losing existing rules
Variations
- Use `ip_address()` for single IPs only and `ip_network()` for both, but catch `ValueError` to filter
- Append to hosts.deny with `open(output_file, "a")` to preserve existing rules
Real-world use cases
- Automating firewall rules by generating hosts.deny entries from threat intelligence feeds during incident response.
- Blocking abusive IPs discovered in server logs by running this script as part of a nightly cron job.
- Providing a quick CLI tool for sysadmins to batch-block IP ranges reported by security monitoring tools.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.