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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 14 views 0 copies

Python code

15 lines
Python 3.9+
from 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

stdout
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

  1. Use `ip_address()` for single IPs only and `ip_network()` for both, but catch `ValueError` to filter
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.