Files
homework09/README.md
2025-12-04 17:41:24 +03:00

363 lines
10 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Домашнее задание 9
## Systemd - создание unit-файла
Для выполнение задания используется Ubuntu Server 24.04
Я немного отошел от домашнего задания, и решил создать свой скрипт.
Работа собственного скрипта будет заключаться в следующем:
1. Скрипт мониторит новые записи в журнале **/var/log/auth.log**
2. Ищет строку с текстом **"Accepted password for"**
3. Если нашел строку, то берет из нее ip адрес по регулярному выражению
4. Сравниваем ip из полученный строки с доверенным ip из конфига **/etc/default/paranoia-shutdown.conf**
5. Если ip не совпадаю, записываем сообщение в лог и **ВЫКЛЮЧАЕМ** сервер!
### Создание bash скрипта
С помощью vi, создаем скрипт в каталоге /opt
```bash
nimda@ubuntu-1:~$ sudo vi /opt/paranoia-shutdown.sh
```
Вставляем туда следующие
```bash
#!/bin/bash
allowIp=$2
pidFile="/var/run/paranoia-shutdown.pid"
start(){
echo $$ > "$pidFile"
tail -f -n0 /var/log/auth.log | while read string
do
if echo "$string" | grep "Accepted password for"
then
ip=$(echo "$string" | grep -o -E '([0-9]{1,3}[\.]){3}[0-9]{1,3}')
if [ "$ip" != "$allowIp" ]
then
logger "Alert!!! Alert!!! Alert!!! Login from not confirmed ip $ip. Faster shutdown!"
systemctl poweroff
fi
fi
done
}
stop(){
kill $(cat "$pidFile")
}
case "$1" in
start)
start;;
stop)
stop;;
restart)
stop
sleep 3
start
;;
*)
echo $"Usage: $0 {start|stop|restart}"
exit 3
esac
```
Сохраняем скрипт, и даем права на запуск
```bash
nimda@ubuntu-1:~$ sudo chmod +x /opt/paranoia-shutdown.sh
```
Создадим конфиг в каталоге /etc/default
```bash
nimda@ubuntu-1:~$ sudo vi /etc/default/paranoia-shutdown.conf
```
Вставим туда одну переменную с ip который будет доверенным.
```bash
allowIp=192.168.50.16
```
### Создание unit
В systemctl создаем новый unit командой
```bash
nimda@ubuntu-1:~$ sudo systemctl edit --force --full paranoia-shutdown
```
Откроется текстовый редактор, туда вставляем следующие
```bash
[Unit]
Description=Paranoia service shutdown. Shuts down the computer if connected from an untrusted IP address.
[Service]
Type=simple
EnvironmentFile=/etc/default/paranoia-shutdown.conf
ExecStart=/opt/paranoia-shutdown.sh start $allowIp
ExecStop=/opt/paranoia-shutdown.sh stop
Restart=on-failure
[Install]
WantedBy=multi-user.target
```
Включаем автозапуск
```bash
nimda@ubuntu-1:~$ sudo systemctl enable paranoia-shutdown
Created symlink /etc/systemd/system/multi-user.target.wants/paranoia-shutdown.service → /etc/systemd/system/paranoia-shutdown.service.
```
Стартуем наш сервис, и смотрим его статус
```bash
nimda@ubuntu-1:~$ sudo systemctl start paranoia-shutdown
nimda@ubuntu-1:~$ sudo systemctl status paranoia-shutdown
● paranoia-shutdown.service - Paranoia service shutdown. Shuts down the computer if connected from an untrusted IP address.
Loaded: loaded (/etc/systemd/system/paranoia-shutdown.service; enabled; preset: enabled)
Active: active (running) since Thu 2025-12-04 10:07:24 UTC; 1s ago
Main PID: 2321 (paranoia-shutdo)
Tasks: 3 (limit: 2202)
Memory: 1008.0K (peak: 1.6M)
CPU: 8ms
CGroup: /system.slice/paranoia-shutdown.service
├─2321 /bin/bash /opt/paranoia-shutdown.sh start 192.168.50.16
├─2324 tail -f -n0 /var/log/auth.log
└─2325 /bin/bash /opt/paranoia-shutdown.sh start 192.168.50.16
Dec 04 10:07:24 ubuntu-1 systemd[1]: Started paranoia-shutdown.service - Paranoia service shutdown. Shuts down the computer if connected from an untrusted IP address..
```
Наш сервис запущен, теперь если подключиться по ssh с любого ip кроме 192.168.50.16 (мой ПК), то сервер выключится.
## Проверка
Сменим IP на ПК и попробуем подключиться.
На сриншоте видно, что при авторизации сервер выполнил команду shutdown!
![9_1](images/9_1.png)
После включения, посмотрим что там в логах, я подключался с ip 192.168.50.66
```bash
nimda@ubuntu-1:~$ cat /var/log/syslog | grep 192.168.50.66 | tail -1
2025-12-04T10:19:30.049414+00:00 ubuntu-1 root: Alert!!! Alert!!! Alert!!! Login from not confirmed ip 192.168.50.66. Faster shutdown!
```
Готово, наш сервис успешно выполняет свой функции!
### Запуск нескольких экземпляров Nginx
Устанавливаем nginx
```bash
nimda@ubuntu-1:~$ sudo apt install nginx -y
[sudo] password for nimda:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
nginx-common
Suggested packages:
fcgiwrap nginx-doc ssl-cert
The following NEW packages will be installed:
nginx nginx-common
...
...
No containers need to be restarted.
No user sessions are running outdated binaries.
No VM guests are running outdated hypervisor (qemu) binaries on this host.
nimda@ubuntu-1:~$
```
Слздаем новый unit **nginx@.service**
```bash
nimda@ubuntu-1:~$ sudo vi /etc/systemd/system/nginx@.service
```
Вставляем туда следующие
```bash
# Stop dance for nginx
# =======================
#
# ExecStop sends SIGSTOP (graceful stop) to the nginx process.
# If, after 5s (--retry QUIT/5) nginx is still running, systemd takes control
# and sends SIGTERM (fast shutdown) to the main process.
# After another 5s (TimeoutStopSec=5), and if nginx is alive, systemd sends
# SIGKILL to all the remaining processes in the process group (KillMode=mixed).
#
# nginx signals reference doc:
# http://nginx.org/en/docs/control.html
#
[Unit]
Description=A high performance web server and a reverse proxy server
Documentation=man:nginx(8)
After=network.target nss-lookup.target
[Service]
Type=forking
PIDFile=/run/nginx-%I.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx-%I.conf -q -g 'daemon on; master_process on;'
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx-%I.conf -g 'daemon on; master_process on;'
ExecReload=/usr/sbin/nginx -c /etc/nginx/nginx-%I.conf -g 'daemon on; master_process on;' -s reload
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx-%I.pid
TimeoutStopSec=5
KillMode=mixed
[Install]
WantedBy=multi-user.target
```
Перечитываем сервисы
```bash
nimda@ubuntu-1:~$ sudo systemctl daemon-reload
```
Теперь создадим еще 2 файла конфигурации, для отдельный демонов nginx.
Скопируем текущий конфиг nginx
```bash
nimda@ubuntu-1:~$ sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx-one.conf
nimda@ubuntu-1:~$ sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx-two.conf
```
С помощь vi отредактируем скопированные файлы.
В файлах nginx-one.conf и nginx-two.conf требуетсянам требует изменить путь до pid файла, чтобы у каждого был свой
```bash
### для nginx-one.conf
#pid /run/nginx.pid;
pid /run/nginx-one.pid;
### для nginx-two.conf
#pid /run/nginx.pid;
pid /run/nginx-two.pid;
```
В обоих файлах закоментируем строку **include /etc/nginx/sites-enabled/*;**
Так же добавим внутрь секции http{} еще одну секцию server{}, и там пропишем разные порты для nginx-one и nginx-two
```bash
### для nginx-one.conf
http {
server {
listen 9001;
}
}
### для nginx-two.conf
http {
server {
listen 9002;
}
}
```
Все сохраняем и запускаем все наши службы nginx
```bash
nimda@ubuntu-1:~$ sudo systemctl start nginx
nimda@ubuntu-1:~$ sudo systemctl start nginx@one
nimda@ubuntu-1:~$ sudo systemctl start nginx@two
```
Проверим статусы служб
```bash
nimda@ubuntu-1:~$ sudo systemctl status nginx nginx@one nginx@two | grep Active
Active: active (running) since Thu 2025-12-04 14:37:25 UTC; 1min 9s ago
Active: active (running) since Thu 2025-12-04 14:37:33 UTC; 1min 1s ago
Active: active (running) since Thu 2025-12-04 14:37:36 UTC; 57s ago
```
```bash
nimda@ubuntu-1:~$ sudo ss -tnulp | grep nginx
tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=3571,fd=5),("nginx",pid=3570,fd=5),("nginx",pid=3569,fd=5))
tcp LISTEN 0 511 0.0.0.0:9002 0.0.0.0:* users:(("nginx",pid=3606,fd=5),("nginx",pid=3605,fd=5),("nginx",pid=3603,fd=5))
tcp LISTEN 0 511 0.0.0.0:9001 0.0.0.0:* users:(("nginx",pid=3589,fd=5),("nginx",pid=3587,fd=5),("nginx",pid=3586,fd=5))
tcp LISTEN 0 511 [::]:80 [::]:* users:(("nginx",pid=3571,fd=6),("nginx",pid=3570,fd=6),("nginx",pid=3569,fd=6))
```
Теперь в системе существую 3 сервиса Nginx
Домашние задание выполнено!