Блокировка отвлекающих сайтов

Блокировка отвлекающих сайтов


import time

from datetime import datetime

import os

import platform


# Список сайтов для блокировки

blocked_sites = [

  "www.youtube.com", "youtube.com",

  "vk.com", "www.vk.com",

  "tiktok.com", "www.tiktok.com"

]


# Время, когда сайты должны быть заблокированы

work_start = 9  # 09:00

work_end = 18  # 18:00


# Файл hosts зависит от ОС

if platform.system() == 'Windows':

  hosts_path = r"C:\Windows\System32\drivers\etc\hosts"

else:

  hosts_path = "/etc/hosts"


redirect_ip = "127.0.0.1"


def is_work_time():

  now = datetime.now().hour

  return work_start <= now < work_end


def block_sites():

  with open(hosts_path, 'r+') as file:

    content = file.read()

    for site in blocked_sites:

      if site not in content:

        file.write(f"{redirect_ip} {site}\n")

  print("[+] Сайты заблокированы.")


def unblock_sites():

  with open(hosts_path, 'r+') as file:

    lines = file.readlines()

    file.seek(0)

    for line in lines:

      if not any(site in line for site in blocked_sites):

        file.write(line)

    file.truncate()

  print("[-] Блокировка снята.")


# Основной цикл

while True:

  if is_work_time():

    block_sites()

  else:

    unblock_sites()

  time.sleep(60)

Report Page