Untitled
unknown
plain_text
9 months ago
11 kB
51
Indexable
import os
import subprocess
import sys
import time
import psutil
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QLabel, QComboBox, QLineEdit, QPushButton, QWidget, QMessageBox
)
from PyQt5.QtCore import QThread, pyqtSignal, QTimer
from PyQt5.QtGui import QFont
# Класс для работы с блокировкой/разблокировкой в отдельном потоке
class InternetBlockerThread(QThread):
update_signal = pyqtSignal(str) # Сигнал для обновления статуса
time_signal = pyqtSignal(int) # Сигнал для отсчета времени
def __init__(self, process_path, block_interval, unblock_interval):
super().__init__()
self.process_path = process_path
self.block_interval = block_interval
self.unblock_interval = unblock_interval
self.is_running = True
def run(self):
while self.is_running:
# Блокировка доступа
self.block_internet_access(self.process_path)
self.update_signal.emit(f"Доступ к интернету заблокирован на {self.block_interval} сек.")
self.countdown(self.block_interval)
if not self.is_running:
break
# Разблокировка доступа
self.unblock_internet_access(self.process_path)
self.update_signal.emit(f"Доступ к интернету разблокирован на {self.unblock_interval} сек.")
self.countdown(self.unblock_interval)
if not self.is_running:
break
def countdown(self, seconds):
"""Отсчет времени."""
for i in range(seconds, 0, -1):
if not self.is_running:
break
self.time_signal.emit(i)
time.sleep(1)
def stop(self):
self.is_running = False
@staticmethod
def block_internet_access(process_path):
rule_name = f"Block {os.path.basename(process_path)} Internet Access"
command = f'netsh advfirewall firewall add rule name="{rule_name}" dir=out program="{process_path}" action=block'
subprocess.run(command, shell=True, check=True)
@staticmethod
def unblock_internet_access(process_path):
rule_name = f"Block {os.path.basename(process_path)} Internet Access"
command = f'netsh advfirewall firewall delete rule name="{rule_name}"'
subprocess.run(command, shell=True, check=True)
# Основное окно приложения
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Internet Blocker")
self.setGeometry(100, 100, 400, 300)
self.setStyleSheet("background-color: #2E3440; color: #D8DEE9;")
# Основной layout
layout = QVBoxLayout()
# Выбор процесса
self.process_label = QLabel("Выберите процесс:")
self.process_label.setFont(QFont("Arial", 10))
self.process_search = QLineEdit()
self.process_search.setFont(QFont("Arial", 10))
self.process_search.setStyleSheet("background-color: #4C566A; color: #D8DEE9;")
self.process_search.setPlaceholderText("Начните вводить название процесса...")
self.process_search.textChanged.connect(self.filter_processes)
layout.addWidget(self.process_label)
layout.addWidget(self.process_search)
self.process_combo = QComboBox()
self.process_combo.setFont(QFont("Arial", 10))
self.process_combo.setStyleSheet("background-color: #4C566A; color: #D8DEE9;")
self.update_process_list()
layout.addWidget(self.process_combo)
# Интервалы
self.block_interval_label = QLabel("Интервал блокировки (сек):")
self.block_interval_label.setFont(QFont("Arial", 10))
self.block_interval_input = QLineEdit("8")
self.block_interval_input.setFont(QFont("Arial", 10))
self.block_interval_input.setStyleSheet("background-color: #4C566A; color: #D8DEE9;")
layout.addWidget(self.block_interval_label)
layout.addWidget(self.block_interval_input)
self.unblock_interval_label = QLabel("Интервал разблокировки (сек):")
self.unblock_interval_label.setFont(QFont("Arial", 10))
self.unblock_interval_input = QLineEdit("8")
self.unblock_interval_input.setFont(QFont("Arial", 10))
self.unblock_interval_input.setStyleSheet("background-color: #4C566A; color: #D8DEE9;")
layout.addWidget(self.unblock_interval_label)
layout.addWidget(self.unblock_interval_input)
# Кнопки
button_layout = QHBoxLayout()
self.start_button = QPushButton("Пуск")
self.start_button.setFont(QFont("Arial", 10))
self.start_button.setStyleSheet("background-color: #5E81AC; color: #D8DEE9;")
self.start_button.clicked.connect(self.start_blocking)
button_layout.addWidget(self.start_button)
self.stop_button = QPushButton("Стоп")
self.stop_button.setFont(QFont("Arial", 10))
self.stop_button.setStyleSheet("background-color: #BF616A; color: #D8DEE9;")
self.stop_button.clicked.connect(self.stop_blocking)
self.stop_button.setEnabled(False)
button_layout.addWidget(self.stop_button)
self.restore_button = QPushButton("Восстановить доступ")
self.restore_button.setFont(QFont("Arial", 10))
self.restore_button.setStyleSheet("background-color: #88C0D0; color: #2E3440;")
self.restore_button.clicked.connect(self.restore_access)
button_layout.addWidget(self.restore_button)
layout.addLayout(button_layout)
# Статус и отсчет времени
self.status_label = QLabel("Статус: Ожидание")
self.status_label.setFont(QFont("Arial", 10))
layout.addWidget(self.status_label)
self.timer_label = QLabel("До следующего изменения: --")
self.timer_label.setFont(QFont("Arial", 10))
layout.addWidget(self.timer_label)
# Установка основного layout
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
# Поток для блокировки
self.blocker_thread = None
def update_process_list(self):
"""Обновляет список процессов в ComboBox."""
self.process_combo.clear()
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
if proc.info['exe']: # Только процессы с известным путем
self.process_combo.addItem(proc.info['name'], proc.info['exe'])
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
def filter_processes(self):
"""Фильтрует процессы по введенному тексту."""
search_text = self.process_search.text().lower()
self.process_combo.clear()
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
if proc.info['exe'] and search_text in proc.info['name'].lower():
self.process_combo.addItem(proc.info['name'], proc.info['exe'])
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
def start_blocking(self):
"""Запускает блокировку."""
process_path = self.process_combo.currentData()
if not process_path:
QMessageBox.warning(self, "Ошибка", "Выберите процесс!")
return
try:
block_interval = int(self.block_interval_input.text())
unblock_interval = int(self.unblock_interval_input.text())
except ValueError:
QMessageBox.warning(self, "Ошибка", "Введите корректные интервалы!")
return
self.blocker_thread = InternetBlockerThread(process_path, block_interval, unblock_interval)
self.blocker_thread.update_signal.connect(self.update_status)
self.blocker_thread.time_signal.connect(self.update_timer)
self.blocker_thread.start()
self.start_button.setEnabled(False)
self.stop_button.setEnabled(True)
self.restore_button.setEnabled(False)
self.status_label.setText("Статус: Запущено")
def stop_blocking(self):
"""Останавливает блокировку."""
if self.blocker_thread:
self.blocker_thread.stop()
self.blocker_thread.wait()
self.blocker_thread = None
self.start_button.setEnabled(True)
self.stop_button.setEnabled(False)
self.restore_button.setEnabled(True)
self.status_label.setText("Статус: Остановлено")
self.timer_label.setText("До следующего изменения: --")
def restore_access(self):
"""Восстанавливает доступ к интернету."""
process_path = self.process_combo.currentData()
if not process_path:
QMessageBox.warning(self, "Ошибка", "Выберите процесс!")
return
InternetBlockerThread.unblock_internet_access(process_path)
self.status_label.setText("Статус: Доступ восстановлен")
QMessageBox.information(self, "Успех", "Доступ к интернету восстановлен!")
def update_status(self, message):
"""Обновляет статус в интерфейсе."""
self.status_label.setText(f"Статус: {message}")
def update_timer(self, seconds):
"""Обновляет отсчет времени."""
self.timer_label.setText(f"До следующего изменения: {seconds} сек")
# Запуск приложения
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle("Fusion") # Современный стиль
window = MainWindow()
window.show()
sys.exit(app.exec_())Editor is loading...
Leave a Comment