Console utility for working with the hosts file in Windows in Python

Sometimes there is a need to make changes to the hosts file in Windows. Along with this need, an idea was born to create a small utility in Python that would simplify the process of editing this file. As a result, WindowsHostsManager appeared – a tool created in just 30 minutes and designed for convenient management of the hosts file.

Description of the program

WindowsHostsManager — is a simple console utility written in Python using standard libraries (os, sys, ctypes and shutil). It is designed exclusively for Windows and allows you to add, delete and view entries in the hosts file, as well as create backup copies and restore the file from them.

Basic commands

  1. add — Add an entry to the hosts file. Example: add 127.0.0.1 example.com

  2. remove — Delete a record by host name. Example: remove example.com

  3. list — Show all current entries in the hosts file.

  4. backup — Create a backup copy of the hosts file.

  5. restore — Restore the hosts file from a backup.

  6. clear — Clear the terminal screen.

  7. help — Show a list of available commands.

  8. exit — Exit the program.

Examples of use

Adding a record:

Enter command: add 127.0.0.1 example.com
Вывод:
Added: 127.0.0.1 example.com

Deleting a record:

Enter command: remove example.com
Вывод:
Removed entries for: example.com

View all entries:

Enter command: list
Вывод:
Current entries in hosts file:
127.0.0.1 localhost
127.0.0.1 example.com

Creating a backup copy:

Enter command: backup
Вывод:
Backup created: C:\Windows\System32\drivers\etc\hosts.back

File recovery:

Enter command: restore
Вывод:
Are you sure you want to restore the hosts file from backup? (yes/no): yes
Hosts file restored from backup: C:\Windows\System32\drivers\etc\hosts.back

Important Notes

Program WindowsHostsManager automatically runs with administrator rights, since privileges are required to make changes to the hosts file. Otherwise, the program will restart and ask for administrator rights.

Differences from analogues

Since I do first and think later, after the work I did I found similar programs. The first one is HostsManthe second one is Hosts ManagerThe difference between my program and these two is that they have a graphical interface (GUI), and my utility is purely console.

Program code

The program was written in just 30 minutes, but already has all the necessary functions for basic management of the hosts file.

import os
import sys
import ctypes
import shutil

HOSTS_PATH = r'C:\Windows\System32\drivers\etc\hosts'
BACKUP_PATH = HOSTS_PATH + '.back'

def is_admin():
    try:
        return os.getuid() == 0
    except AttributeError:
        return ctypes.windll.shell32.IsUserAnAdmin() != 0

def read_hosts():
    with open(HOSTS_PATH, 'r') as file:
        return file.readlines()

def write_hosts(lines):
    with open(HOSTS_PATH, 'w') as file:
        file.writelines(lines)

def add_entry(ip, hostname):
    lines = read_hosts()
    entry = f"{ip} {hostname}\n"
    
    if entry not in lines:
        lines.append(entry)
        write_hosts(lines)
        print(f"Added: {entry.strip()}")
    else:
        print(f"Entry already exists: {entry.strip()}")

def remove_entry(hostname):
    lines = read_hosts()
    lines = [line for line in lines if not line.endswith(f"{hostname}\n")]
    write_hosts(lines)
    print(f"Removed entries for: {hostname}")

def list_entries():
    lines = read_hosts()
    if lines:
        print("Current entries in hosts file:")
        for line in lines:
            print(line.strip())
    else:
        print("No entries found in the hosts file.")

def print_help():
    print("Commands:")
    print("  add      - Add an entry (e.g., add <IP> <hostname>)")
    print("  remove   - Remove an entry (e.g., remove <hostname>)")
    print("  list     - List all entries in the hosts file")
    print("  backup   - Create a backup of the hosts file")
    print("  restore  - Restore the hosts file from backup")
    print("  clear    - Clear the terminal screen")
    print("  help     - Show this help message")
    print("  exit     - Exit the application")

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def backup_hosts():
    try:
        shutil.copy2(HOSTS_PATH, BACKUP_PATH)
        print(f"Backup created: {BACKUP_PATH}")
    except IOError as e:
        print(f"Failed to create backup: {e}")

def restore_hosts():
    if os.path.exists(BACKUP_PATH):
        confirm = input("Are you sure you want to restore the hosts file from backup? (yes/no): ").strip().lower()
        if confirm == 'yes':
            try:
                shutil.copy2(BACKUP_PATH, HOSTS_PATH)
                print(f"Hosts file restored from backup: {BACKUP_PATH}")
            except IOError as e:
                print(f"Failed to restore hosts file: {e}")
        else:
            print("Restore operation canceled.")
    else:
        print("No backup file found.")

def main():
    while True:
        print("Enter command:", end=' ')
        command = input().strip().lower()

        if command.startswith('add'):
            _, ip, hostname = command.split(maxsplit=2)
            add_entry(ip, hostname)
        elif command.startswith('remove'):
            _, hostname = command.split(maxsplit=1)
            remove_entry(hostname)
        elif command == 'list':
            list_entries()
        elif command == 'backup':
            backup_hosts()
        elif command == 'restore':
            restore_hosts()
        elif command == 'help':
            print_help()
        elif command == 'clear':
            clear_screen()
        elif command == 'exit':
            print("Exiting the application...")
            break
        else:
            print("Invalid command. Type 'help' for a list of commands.")

if __name__ == "__main__":
    if not is_admin():
        print("This script needs to be run with administrator privileges.")
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
    else:
        main()

Repository on GitHub

The source code for the WindowsHostsManager utility is available at my GitHub repository. You can download, test and, if necessary, change the code to suit your needs. I will be glad if you leave your suggestions or improvements in the issues or pull requests section.

This utility is a great example of how Python allows you to create simple yet powerful tools to solve everyday problems.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *