В данной статье я расскажу как настроить обход блокировки сайтов в Linux на примере Ubuntu 22.04. Для обхода блокировки будет использоваться утилита zapret. Как настроить обход для Windows я рассказал в этой статье.
zapret v.48
Автономное, без задействования сторонних серверов, средство противодействия DPI. Может помочь обойти блокировки или замедление сайтов http(s), сигнатурный анализ tcp и udp протоколов, например с целью блокировки VPN.
Первым делом необходимо установить пакеты git и curl если они у вас не установлены.
apt install git curl
Далее делаем клон репозитория bol-van/zapret
git clone https://github.com/bol-van/zapret.git
Переходим в каталог zapret и устанавливаем бинарники
Теперь нам нужно определить какой способ обхода блокировки нам подходит. Для этого пишем:
./blockcheck.sh | tee /tmp/blockcheck.txt
Далее нам будут заданы несколько вопросов:
specify domain(s) to test. multiple domains are space separated. domain(s) (default: rutracker.org) : Домен(ы) для тестирования методов обхода блокировки. Я указал rutracker.org и nnmclub.to
ip protocol version(s) — 4, 6 or 46 for both (default: 4) : Версия протокола IP. У меня 4.
check http (default : Y) (Y/N) ? Проверять ли доступность сайта по протоколу HTTP. Говорим да.
check https tls 1.2 (default : Y) (Y/N) ? Проверять ли доступность сайта по протоколу HTTPS с TLS v1.2. Тоже да.
check https tls 1.3 (default : N) (Y/N) ? Тоже самое, что и предыдущее только для TLS версии 1.3. Я оставил по умолчанию, т. е. нет.
do not verify server certificate (default : N) (Y/N) ? Проверять ли SSL сертификат? Тоже оставляем по умолчанию, нет.
how many times to repeat each test (default: 1) Сколько раз нужно повторять тест. Я оставил по умолчанию.
do all tests despite of result ? (default : N) (Y/N) ? Делать все тесты несмотря на результат. По умолчанию.
После этого пойдет тестирование. После завершения тестирования смотрим файл /tmp/blockcheck.txt и ищем в нем !!!!! AVAILABLE !!!!!. Это и будет наш обход блокировки сайтов в linux. Их может быть несколько. У меня на Ростелеком это:
- checking tpws --hostcase
!!!!! AVAILABLE !!!!!
- checking tpws --hostspell=hoSt
!!!!! AVAILABLE !!!!!
- checking tpws --split-http-req=method
!!!!! AVAILABLE !!!!!
- checking tpws --split-http-req=method --hostcase
!!!!! AVAILABLE !!!!!
- checking tpws --split-http-req=host
!!!!! AVAILABLE !!!!!
- checking tpws --split-http-req=host --hostcase
!!!!! AVAILABLE !!!!!
- checking tpws --hostdot
!!!!! AVAILABLE !!!!!
- checking tpws --hosttab
!!!!! AVAILABLE !!!!!
- checking tpws --hostnospace
!!!!! AVAILABLE !!!!!
- checking tpws --methodspace
!!!!! AVAILABLE !!!!!
- checking tpws --methodeol
!!!!! AVAILABLE !!!!!
- checking tpws --unixeol
!!!!! AVAILABLE !!!!!
- checking tpws --hostpad=1024
!!!!! AVAILABLE !!!!!
- checking tpws --hostpad=2048
!!!!! AVAILABLE !!!!!
- checking tpws --hostpad=4096
!!!!! AVAILABLE !!!!!
- checking tpws --hostpad=8192
!!!!! AVAILABLE !!!!!
- checking tpws --hostpad=16384
!!!!! AVAILABLE !!!!!
Запускаем скрипт install_easy.sh
./install_easy.sh
Далее нам также будут заданы несколько вопростов:
easy install is supported only from default location : /opt/zapret currently its run from /home/adm1/zapret do you want the installer to copy it for you (default : N) (Y/N) ? Отвечаем да.
select firewall type : 1 : iptables 2 : nftables your choice (default : iptables) : Какой фаервол используется. У меня iptables.
enable ipv6 support (default : N) (Y/N) ? Использование протокола IPv6. Оставляем по умолчанию, нет.
select MODE : 1 : tpws 2 : tpws-socks 3 : nfqws 4 : filter 5 : custom your choice (default : tpws) : Режим обхода блокировки. Опираемся на результаты проверки. У меня это tpws.
TPWS_OPT=»—hostspell=HOST —split-http-req=method —split-pos=3″ do you want to edit the options (default : N) (Y/N) ? Хотим ли мы изменить параметры для режима. Также опираемся на результаты проверки. Я поменял на —hostspell=hoSt.
LAN interface : 1 : NONE 2 : enp0s3 3 : lo your choice (default : NONE) : Так как мы настраиваем на клиенте, то выбираем вариант NONE.
WAN filtering works only for local outgoing traffic ! WAN interface : 1 : ANY 2 : enp0s3 3 : lo your choice (default : ANY) : На каком WAN интерфейсе будет работать фильтрация. Можно оставить по умолчанию. enable http support (default : Y) (Y/N) ? Поддержка http. Да.
enable https support (default : Y) (Y/N) ? Поддержка https. Да.
В данной статье я расскажу как добавить мониторинг ИБП в Home Assistant на примере CyberPower Value500EI.
У данной модели есть USB разъем для мониторинга состояния ИБП. Для мониторинга у CyberPower есть своя утилита под названием PowerPanel. Скачать ее можно с сайта производителя. У меня на домашнем сервере стоит Ubuntu 20.04, по этому я скачал PowerPanel for Linux 64bit (deb).
Подключаем ИБП через USB и устанавливаем PowerPanel:
В ответ, если все нормально, должны увидеть примерно следующее:
The UPS information shows as following:
Properties:
Model Name................... Value500EI
Firmware Number.............. BZAB100.B31
Rating Voltage............... 230 V
Rating Power................. 275 Watt(500 VA)
Current UPS status:
State........................ Normal
Power Supply by.............. Utility Power
Utility Voltage.............. 224 V
Output Voltage............... 226 V
Battery Capacity............. 100 %
Remaining Runtime............ 31 min.
Load......................... 49 Watt(18 %)
Line Interaction............. None
Test Result.................. Unknown
Last Power Event............. Blackout at 2022/09/13 23:53:27 for 7 sec.
В файле /etc/pwrstatd.conf настраиваем выключение компьютера через время после перехода на резервное питание или при разряде аккумулятора на определенный процент. Также можно настроить отправку E-Mail или выполнение произвольного скрипта. После изменения перезапускаем демона:
service pwrstatd restart
У меня настроено выключение сервера при разряде аккумулятора до 35%. Мой конфиг:
# pwrstatd configuration file
#
# You must restart pwrstatd after changing this file in order for changes to take effect.
# Ex:/etc/init.d/pwrstatd restart
#
# Action setting for event of Power Failure
#
# A delay time in seconds since event of Power Failure occur then to run shell
# script and shutdown system. Allowed range is 0 ~ 3600. Default is 60 sec.
powerfail-delay = 60
# Enable to run shell script when the event of Power Failure occur.
# The allowed options are yes and no. Default is yes.
powerfail-active = yes
# Assign a path of script file for event of Power Failure.
# The default is /etc/pwrstatd-powerfail.sh
powerfail-cmd-path = /etc/pwrstatd-powerfail.sh
# How much time in seconds to take script running for event of Power Failure.
# The allowed range is 0 ~ 3600. Default is 0 sec.
powerfail-duration = 0
# Allow Daemon to shutdown system for event of Power Failure.
# The allowed options are yes and no. Default is yes.
powerfail-shutdown = no
#
# Action setting for event of Battery Low
#
# A threshold of Battery Capacity, If the battery capacity is lower than this
# value and a event of Battery Low will be identified. The unit is percentage.
# The allowed range is 0 ~ 90. Default is 35 %.
lowbatt-threshold = 35
# A threshold of Remaining Runtime, If the Remaining Runtime is lower than this
# value and a event of Battery Low will be identified. The unit is second.
# The allowed range is 0 ~ 3600. Default is 300 sec.
# Note: When meet this condition the below 'shutdown-sustain' property
# will be ignored.
runtime-threshold = 300
# Enable to run shell script when the event of Battery Low occur.
# The allowed options are yes and no. Default is yes.
lowbatt-active = yes
# Assign a path of script file for event of Battery Low.
# The default is /etc/pwrstatd-lowbatt.sh
lowbatt-cmd-path = /etc/pwrstatd-lowbatt.sh
# How much time in seconds to take script running for event of Battery Low.
# The allowed range is 0 ~ 60. Default is 0 sec.
lowbatt-duration = 0
# Allow Daemon to shutdown system for event of Battery Low.
# The allowed options are yes and no. Default is yes.
lowbatt-shutdown = yes
# Turn UPS alarm on or off.
# The allowed options are yes and no. Default is yes.
enable-alarm = yes
# The necessary time in seconds for system shutdown.
# The UPS will turn power off when this time is expired.
# The allowed range is 0 ~ 3600. Default is 600 sec.(10 min.)
# If the computer shutdown is cause by low runtime condition, the UPS will
# turn power off when the time is expired that time is assigned on
# 'runtime-threshold' property and it is no longer to refer the
# 'shutdown-sustain' property.
shutdown-sustain = 600
# Daemon will turn UPS power off once it ask system shutdown cause by a power
# event. Allowed options are yes and no. Default is yes.
turn-ups-off = yes
# The period of polling UPS in seconds.
# The allowed range is 1 ~ 60. Default is 3 sec.
ups-polling-rate = 3
# the period of re-try to find available UPS in seconds since find nothing at
# last time. The allowed range is 1 ~ 300. Default is 10 sec.
ups-retry-rate = 10
# Prohibiting daemon to provide communication mechanism for client, such as
# pwrstat command. normally, it should be 'no'. It can be 'yes' if any security
# consideration. Allowed options are yes and no. Default is no.
prohibit-client-access = no
# The pwrstatd accepts four types of device node which includes the 'ttyS',
# 'ttyUSB', 'hiddev', and 'libusb' for communication with UPS. The pwrstatd
# defaults to enumerate all acceptable device nodes and pick up to use an
# available device node automatically. But this may cause a disturbance to the
# device node which is occupied by other software. Therefore, you can restrict
# this enumerate behave by using allowed-device-nodes option. You can assign
# the single device node path or multiple device node paths divided by a
# semicolon at this option. All groups of 'ttyS', 'ttyUSB', 'hiddev', or
# 'libusb' device node are enumerated without a suffix number assignment.
# Note, the 'libusb' does not support suffix number only.
#
# For example: restrict to use ttyS1, ttyS2 and hiddev1 device nodes at /dev
# path only.
# allowed-device-nodes = /dev/ttyS1;/dev/ttyS2;/dev/hiddev1
#
# For example: restrict to use ttyS and ttyUSB two groups of device node at
# /dev,/dev/usb, and /dev/usb/hid paths(includes ttyS0 to ttySN and ttyUSB0 to
# ttyUSBN, N is number).
# allowed-device-nodes = ttyS;ttyUSB
#
# For example: restrict to use hiddev group of device node at /dev,/dev/usb,
# and /dev/usb/hid paths(includes hiddev0 to hiddevN, N is number).
# allowed-device-nodes = hiddev
#
# For example: restrict to use libusb device.
# allowed-device-nodes = libusb
allowed-device-nodes =
# Daemon will hibernate system to instead of system shutdown when power
# event occur. Allowed options are yes and no. Default is no.
hibernate = no
# Enable cloud solution.
# The allowed options are yes and no. Default is no.
cloud-active = no
# Account for cloud server login.
cloud-account =
Далее в Docker необходимо установить контейнер, который будет парсить эту информацию и передавать в MQTT брокер:
Проверяем работоспособность по ссылкам: http://192.168.0.24:5003/health и http://192.168.0.24:5003/mqtthealth. Не забудьте поменять IP на свой. Если все нормально, то мы увидим:
{"code":"SUCCESS","message":"OK"}
Отлично! Данные отправляются в MQTT. Теперь необходимо достать их в Home Assistant. Для этого создаем сенсоры:
Сколько не искал как настроить ZM, чтобы он сам удалял старые записи, так и не смог найти. Пришлось сделать свой костыль на PHP. Скрипт писался исключительно для себя, и не претендует на правильность.
<?php
$servername = ""; // IP адрес MySQL сервера
$database = "zm"; // Имя БД
$username = ""; // Имя пользователя БД
$password = ""; // Пароль пользователя БД
$path = ""; // Путь к папке с записями
$interval = "7"; // Удалять записи старше N дней
// Создаем соединение
$mysqli = new mysqli($servername, $username, $password, $database);
// Получаем записи старше N дней
$result = $mysqli->query('SELECT * FROM `Events` WHERE StartDateTime < (NOW() - INTERVAL '.$interval.' DAY)');
$rows = $result->fetch_all(MYSQLI_ASSOC);
// Форматируем дату
$arrDates = array();
foreach($rows as $row) {
$date = explode(' ', $row['StartDateTime'])[0];
array_push($arrDates, $date);
}
// Удаляем дубликаты дат
$arrDates = array_unique($arrDates);
// Удаляем папки старше N дней
foreach($arrDates as $date) {
// Удаление для каждого монитора отдельно
exec('rm -R '.$path.'5/'.$date);
exec('rm -R '.$path.'6/'.$date);
}
// Удаляем записи старше N дней
$mysqli->query('DELETE FROM `Events` WHERE StartDateTime < (NOW() - INTERVAL '.$interval.' DAY)');
// Закрываем соединение
$mysqli->close();
Скрипт запускается командой php script.php из консоли и может быть добавлен в cron.
В новых версиях Ubuntu убрали rc.local. Но так как я уже привык к нему, а через crontab не очень удобно, то я решил вернуть его обратно. Создаем файл rc.local:
Для начала необходимо создать группу, и добавить в нее нашего юзера.
sudo groupadd dev
sudo usermod -aG dev boris
Далее надо изменить группу для нашей папки
sudo chown -R root:dev /var/www
И соответственно выставить на папку права для группы
sudo chmod -R 755 /var/www
Теперь пользователь boris имеет право чтение/запись файлов в директории /var/www. Что бы дать еще одному пользователю доступ, достаточно будет просто добавить его в группу.
Теперь необходимо добавить TXT запись домена. Субдомен указываем mail._domainkey, а значение берем из файла /etc/opendkim/keys/domain.com/mail.txt Пример: