-
Notifications
You must be signed in to change notification settings - Fork 5
/
ri.sh
1283 lines (1174 loc) · 48.2 KB
/
ri.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#set -euo pipefail
#IFS=$'\n\t'
#Вспомогательное внутри сценария
LOG_FILE="/root/rish/logfile_rish_install.log"
# Путь к конфигурационному файлу
config_file="/root/rish/rish_config.sh"
# Проверка на существование файла лога, если он не существует - создать его
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
fi
# Функция для проверки, был ли шаг выполнен
check_step() {
local step=$1
grep -Fxq "$step" "$LOG_FILE"
}
# Функция для записи выполненного шага
mark_step_completed() {
local step=$1
echo "$step" >> "$LOG_FILE"
}
# Проверяем существование файла
if [ ! -f "$config_file" ]; then
# Создаем файл, если он не существует
touch "$config_file"
fi
# Функция для добавления переменной и комментария, если они отсутствуют в конфиге
add_var_if_not_exists() {
local var_name="$1"
local var_value="$2"
if ! grep -P "^\s*${var_name}\s*=" "$config_file" > /dev/null 2>&1; then
echo -e "$var_value" >> "$config_file"
fi
}
SCRIPTVERSION='1.0.1'
GREEN='\033[0;32m'
RED='\033[0;31m'
LRED='\033[1;31m'
VIOLET='\033[0;35m'
WHITE='\033[0m'
CURSORUP='\033[1A'
ERASEUNTILLENDOFLINE='\033[K'
ServerArch=$( arch )
OS_VERSION=$( hostnamectl | grep -Eo 'Operating.*' | sed 's@^[^0-9]*\([0-9]\+\).*@\1@' )
SUPPORTED_OS='Fedora|Rocky|AlmaLinux|CentOS|Red Hat Enterprise Linux Server|Oracle|ClearOS|Scientific Linux'
size=$(stty size)
lines=${size% *}
columns=${size#* }
upperX=1
upperY=1
downY=$((${lines}/2))
rim=$(( ${downY} - 2 ))
whereCursorIs="down"
# save the home dir
declare _script_name=${BASH_SOURCE[0]}
declare _script_dir=${_script_name%/*}
if [[ "$_script_name" == "$_script_dir" ]]
then
# _script name has no path
_script_dir="."
fi
# convert to absolute path
_script_dir=$(cd ${_script_dir}; pwd -P)
export RISH_HOME=${_script_dir}
cd ${RISH_HOME} || exit
source windows.sh
source clonesite.sh
source checkip.sh
source php_multi_install.sh
source mariadb_install.sh
source create_hotlist.sh
source create_swapfile.sh
if (( lines < 40 || columns < 140 )); then
echo
echo "Размер окна вашего терминала слишком маленький."
echo -e "Советуем увеличить окно терминала до размера ${RED}140x40${WHITE} символов."
echo "Иначе вывод на экран возможно будет некорректным."
echo
if vertical_menu "current" 2 0 5 "Остановить выполнение скрипта установки" "Хорошо понятно. Продолжаем"
then
echo -e "Продолжить выполнение можно выполнив команду ${GREEN}/root/rish/ri.sh${WHITE}"
exit 1
fi
fi
# Если настройка скрипта уже была произведена, но сессия не была перезапущена - подгрузим пароль базы данных
if [[ -z "${MYSQLPASS}" ]]
then
if grep -q "MYSQLPASS" ~/.bashrc
then
MYSQLPASS=`cat ~/.bashrc | grep MYSQLPASS | awk -F= '{ print $2}'`
fi
fi
Up() {
if [[ ${whereCursorIs} == "down" ]]
then
downY=$( get_cursor_row )
whereCursorIs="up"
# ограничить скрол верхней части экрана
echo -e ${ESC}"[1;${rim}r"
cursor_to ${upperY} 1
fi
}
Down() {
if [[ ${whereCursorIs} == "up" ]]
then
upperY=$( get_cursor_row )
echo -e ${ESC}"[$(( ${rim}+2));${lines}r"
# ограничить скрол нижней частью экрана
cursor_to ${downY} 1
whereCursorIs="down"
fi
}
RemoveRim () {
echo -e ${ESC}"[;r"
cursor_to $(( ${rim} +1 )) 1
echo -en ${ESC}"[0J"
}
clear
# Рисуем разделительную линию
cursor_to $(( ${rim} +1 )) 1
repl "─" $(( ${columns} ))
cursor_to $(( ${rim} +2 )) 1
Up
if (type lsb_release > /dev/null 2>&1); then
CURRENT_OS=$(lsb_release -d -s)
echo -e "Ваша версия Linux: ${RED}$CURRENT_OS${WHITE}"
elif [[ -f /etc/system-release ]]; then
CURRENT_OS=$(head -1 /etc/system-release)
echo -e "Ваша версия Linux: ${GREEN}$CURRENT_OS${WHITE}"
echo
elif [[ -f /etc/issue ]]; then
CURRENT_OS=$(head -2 /etc/issue)
echo -e "Ваша версия Linux: ${RED}$CURRENT_OS${WHITE}"
else
echo -e "${RED}Невозможно определить вашу версию Linux${WHITE}"
exit 1
fi
if ! echo ${CURRENT_OS} | egrep -q "$SUPPORTED_OS"
then
echo -e "Ваш дистрибутив Linux ${RED}не поддерживается${WHITE}"
exit 1
fi
if echo ${CURRENT_OS} | grep -Eq "Fedora"
then
FedoraVersion=$( cat /etc/fedora-release | sed 's@^[^0-9]*\([0-9]\+\).*@\1@' )
fi
Install() {
if ! rpm -q $@ >/dev/null 2>&1; then
Up
echo -e "Ставим ${GREEN}$@${WHITE}"
Down
if yum -y install $@; then
(( upperY -- ))
Up
echo -e "${GREEN}$@${WHITE} установлен"
else
Up
echo -e "Установить ${RED}$@${WHITE} не удалось, очищаем кэш и пытаемся снова"
# Очистка кэша yum и повторная попытка установки
Down
yum clean all
yum makecache
if yum -y install $@; then
Up
echo -e "${GREEN}$@${WHITE} установлен после очистки кэша"
else
Up
echo -e "Установить ${RED}$@${WHITE} не удалось даже после очистки кэша"
RemoveRim
exit 1
fi
fi
echo
else
Up
echo -e "${GREEN}$@${WHITE} уже установлен"
fi
Down
}
OpenFirewall() {
if command -v firewall-cmd >/dev/null 2>&1 && systemctl status firewalld >/dev/null
then
if firewall-cmd --list-all | grep http > /dev/null && firewall-cmd --list-all | grep https > /dev/null
then
echo -e "${GREEN}Firewall${WHITE} уже открыт"
else
echo -e "Открываем ${GREEN}firewall${WHITE}"
Down
ZoneName=$(firewall-cmd --get-default-zone)
firewall-cmd --zone=${ZoneName} --permanent --add-service=http
firewall-cmd --zone=${ZoneName} --permanent --add-service=https
firewall-cmd --reload
Up
fi
else
echo -e "${GREEN}Firewall${WHITE} не установлен"
Install "firewalld"
Down
systemctl enable firewalld
systemctl start firewalld
ZoneName=$(firewall-cmd --get-default-zone)
firewall-cmd --zone=${ZoneName} --permanent --add-service=http
firewall-cmd --zone=${ZoneName} --permanent --add-service=https
firewall-cmd --reload
Up
fi
}
process_ssh_config_file() {
local config_file=$1
# Резервное копирование файла конфигурации
cp "$config_file" "${config_file}.bak"
# Удаление всех строк с PasswordAuthentication
sed -i '/^#\?PasswordAuthentication/d' "$config_file"
# Добавление строки с отключением аутентификации по паролю перед первым блоком Match
awk '/^Match/ && !done {print "PasswordAuthentication no"; done=1} 1' "$config_file" >"${config_file}.tmp" && mv "${config_file}.tmp" "$config_file"
# Если строка PasswordAuthentication no не была добавлена, добавить её в конец файла
if ! grep -q "^PasswordAuthentication no" "$config_file"; then
echo "PasswordAuthentication no" >>"$config_file"
fi
}
# shellcheck disable=SC2120
CreateUser() {
local NAME
local default_username="$1" # Получаем первый параметр, переданный в функцию
# try to create user
while true; do
echo -e "При создании пользователя используйте только латинские буквы."
echo -e -n "${WHITE}Введите имя пользователя (для выхода наберите EXIT):${GREEN}"
if [[ -z "$default_username" ]]; then
read -e -p " " NAME # Не задаем значение по умолчанию, если параметр пустой
else
read -e -p " " -i "$default_username" NAME # Используем переданный параметр как значение по умолчанию
fi
if [[ -z "${NAME}" ]]
then
continue
fi
if [[ ${NAME} == "EXIT" ]] || [[ ${NAME} == "exit" ]]
then
break
fi
NAME=$( echo ${NAME} | tr -cd "[:alnum:]")
echo -e "${WHITE}Будет создан пользователь с именем: ${VIOLET}${NAME}${WHITE}"
if vertical_menu "current" 2 0 5 "Да" "Нет"
then
if id -u ${NAME} >/dev/null 2>&1
then
echo -e "${WHITE}Такой пользователь уже есть ${LRED}${NAME}${WHITE}"
else
break
fi
fi
done
if [[ ${NAME} == "EXIT" ]] || [[ ${NAME} == "exit" ]]
then
echo -e ${WHITE}
return 0
else
echo -e "${WHITE}Создаем пользователя ${GREEN}${NAME}${WHITE}"
fi
echo -e ${WHITE}
echo "При создании новых сайтов Joomla требуется указать учетную запись для администратора."
echo "Вы можете указать имя этой учетной записи, чтобы в дальнейшем не тратить время на ее изменение."
echo -e "Если вы не укажете имя сейчас - оно будет создано автоматически. "
echo -e "Изменить его можно будет в файле ${GREEN}/home/${NAME}/.pass.txt${WHITE}"
echo
echo "Введите имя учетной записи для создания сайтов по умолчанию (Обычно это ваш E-mail)"
read -e -p "(Можно не заполнять - нажмите Enter)" DEFAULTSITEACCOUNT
if id -u ${NAME} >/dev/null 2>&1
then
echo -e "${WHITE}Такой пользователь уже есть ${LRED}${NAME}${WHITE}"
return 1
fi
useradd -s /sbin/nologin ${NAME}
pass=$( tr -dc A-Za-z0-9 < /dev/urandom | head -c 16 | xargs )
echo ${NAME}:${pass} | chpasswd
pass2=$( tr -dc A-Za-z0-9 < /dev/urandom | head -c 16 | xargs )
echo "Database: ${pass2}" > /home/${NAME}/.pass.txt
echo -e "Пароль пользователя ${NAME}: ${GREEN}"${pass}${WHITE}
echo "${NAME}: ${pass}" >> /home/${NAME}/.pass.txt
echo -e "Пароль для баз данных ${NAME}: ${GREEN}"${pass2}${WHITE}
pass3=$( tr -dc A-Za-z0-9 < /dev/urandom | head -c 16 | xargs )
if [[ -z ${DEFAULTSITEACCOUNT} ]]
then
DEFAULTSITEACCOUNT="info@${NAME}.com"
fi
echo -e "Учетная запись по умолчанию: ${GREEN}${DEFAULTSITEACCOUNT}${WHITE}"
echo "defaultsiteaccount ${DEFAULTSITEACCOUNT} ${pass3}" >> /home/${NAME}/.pass.txt
chmod go-rwx /home/${NAME}/.pass.txt
chown ${NAME}:${NAME} /home/${NAME}/.pass.txt
echo -e "Пароли записаны в файл ${GREEN}/home/${NAME}/.pass.txt${WHITE}"
usermod -a -G sftp ${NAME}
usermod -aG ${NAME} apache
mkdir /var/www/${NAME}
mkdir /var/www/${NAME}/logs
mkdir /var/www/${NAME}/www
chown ${NAME}:${NAME} /var/www/${NAME}/www
chown ${NAME}:${NAME} /var/www/${NAME}/logs
# устанавливаем владельцем siteuser
# создаем папку /home/siteuser/.ssh
mkdir /home/${NAME}/.ssh
chown ${NAME}:${NAME} /home/${NAME}/.ssh
# создаем файл /home/siteuser/.ssh/authorized_keys для ключей доступа для юзера
echo "" > /home/${NAME}/.ssh/authorized_keys
chown ${NAME}:${NAME} /home/${NAME}/.ssh/authorized_keys
# Создаем папки и устанавливаем их владельцем siteuser
mkdir /var/www/${NAME}/session
mkdir /var/www/${NAME}/wsdlcache
mkdir /var/www/${NAME}/slowlog
mkdir /var/www/${NAME}/tmp
chown ${NAME}:${NAME} /var/www/${NAME}/session
chown ${NAME}:${NAME} /var/www/${NAME}/wsdlcache
chown ${NAME}:${NAME} /var/www/${NAME}/slowlog
chown ${NAME}:${NAME} /var/www/${NAME}/tmp
# Удаляем конфигурацию php по умолчанию (это файлы типа php74-php.conf)
find /etc/httpd/conf.d -type f -name 'php[0-9][0-9]-php.conf' -exec rm -f {} +
create_hotlist
if mariadb -e "CREATE USER ${NAME}@localhost IDENTIFIED BY '${pass2}';"
then
echo -e "пользователь ${GREEN}${NAME}${WHITE} успешно создан"
else
echo -e "во время создания пользователя ${RED}${NAME}${WHITE} MySQL произошла ошибка"
fi
}
DeleteDatabase() {
echo -e "Вы хотите удалить базу данных ${LRED}${1}${WHITE}?"
if vertical_menu "current" 2 0 5 "Нет" "Да"
then
echo "База данных не была удалена"
return 1
elif (( $? == 255 ))
then
echo "База данных не была удалена"
return 1
fi
echo -e ${CURSORUP}${ERASEUNTILLENDOFLINE}
if mysqladmin -f drop ${1}
then
echo -e "База данных ${GREEN}${1}${WHITE} удалена"
else
echo -e "При удалении базы данных ${RED}${1}${WHITE} произошли ${RED}ошибки${WHITE}"
fi
}
DeleteUser() {
# если папка не пуста, то отказываться удалять пользователя
if [[ -n $( ls -A /var/www/${1}/www ) ]]
then
echo "У пользователя есть неудаленные сайты. Вначале удалите их."
echo -e -n ${RED}
cd /var/www/${1}/www
# выводим директории
ls -d */ | cut -f1 -d'/'
# и файлы
echo -e -n ${LRED}
ls -Sp | grep -v '/'
echo -e ${WHITE}
return 1
fi
# проверим на предмет неудаленных баз данных
SiteuserMysqlPass=`cat /home/${1}/.pass.txt | grep Database | awk '{ print $2}'`
bases=( `mariadb -u${1} -p${SiteuserMysqlPass} --batch -e "SHOW DATABASES" | tail -n +3` )
if (( ${#bases[@]} > 0 ))
then
echo "У пользователя есть неудаленные базы данных:"
echo -e ${RED}
for i in "${bases[@]}"; do
echo ${i}
done
echo -e ${WHITE}
echo "Вначале удалите их"
return 1
fi
echo -e "Удалить пользователя ${RED}${1}${WHITE}?"
if vertical_menu "current" 2 0 5 "Нет" "Да"
then
echo -e ${CURSORUP}"Пользователь ${GREEN}$1${WHITE} не удален."
return 1
fi
rm -rf /var/www/${1}
# Удаляем пользователя изо всех php пулов
mapfile -t installed_versions < <(rpm -qa | grep php | grep -oP 'php[0-9]{2}' | sort -r | uniq)
for installed in "${installed_versions[@]}"; do
rm -f /etc/opt/remi/${installed}/php-fpm.d/${1}*
if [ -z "$(find /etc/opt/remi/${installed}/php-fpm.d -maxdepth 1 -type f -name '*.conf')" ]; then
# Если файлов .conf нет, проверяем наличие файла www.conf.old для переименования
if [ -f "/etc/opt/remi/${installed}/php-fpm.d/www.conf.old" ]; then
# Переименовываем файл www.conf.old в www.conf
mv "/etc/opt/remi/${installed}/php-fpm.d/www.conf.old" "/etc/opt/remi/${installed}/php-fpm.d/www.conf"
echo -e "Файл ${GREEN}www.conf${WHITE} восстановлен по умолчанию, так как все пулы этой версии php удалены."
else
echo -e "Файла ${RED}www.conf.old${WHITE} в папке пула ${RED}/etc/opt/remi/${installed}/php-fpm.d/${WHITE} нет!."
echo "Невозможно восстановить его автоматически."
echo -e "Нужно восстановить этот файл вручную, иначе ${installed} перестанет работать."
fi
fi
if ! /opt/remi/${installed}/root/usr/sbin/php-fpm -t
then
echo "Ошибка в настройках. ${installed}-fpm не был перезагружен"
else
systemctl restart "${installed}-php-fpm"
echo "${installed}-fpm был перезагружен"
fi
done
gpasswd -d apache ${1}
userdel --remove ${1}
create_hotlist
mariadb -e "DROP USER IF EXISTS ${1}@localhost;"
echo -e "Пользователь ${RED}$1${WHITE} был удален."
}
echo -e "${GREEN}System memory:${WHITE}"
free -m
echo ""
echo -e "${GREEN}Disk space:${WHITE}"
df -h -P -l -x tmpfs -x devtmpfs
echo ""
if ! grep -q "MYSQLPASS" ~/.bashrc; then
STEP="Проверка обновлений сервера выполнена"
if ! check_step "$STEP"; then
echo -n "Проверяем обновления сервера... "
if dnf check-update >/dev/null; then
echo "Сервер не требует обновления"
else
Down
echo ""
echo 'Обновляем сервер? '
echo 'Настоятельно рекомендуем обновить при первом запуске.'
vertical_menu "current" 2 0 5 "Да" "Нет" "Выйти"
ret=$?
if ((ret > 1)); then
exit 1
fi
if ((ret == 0)); then
((upperY--))
Up
echo
echo -e "Идет обновление сервера..."${ERASEUNTILLENDOFLINE}
Down
yum update -y
fi
Up
fi
mark_step_completed "$STEP"
fi
STEP="Установка языковых пакетов"
if ! check_step "$STEP"; then
Install langpacks-en glibc-all-langpacks
mark_step_completed "$STEP"
fi
fi
if ! grep -q "MYSQLPASS" ~/.bashrc; then
# we think that it is the first run of the script
STEP="Установка кодировки консоли"
if ! check_step "$STEP"; then
if localectl status | grep -q UTF-8; then
echo
echo -e "Кодировка консоли уже установлена правильно - ${GREEN}UTF-8${WHITE}."
else
localectl set-locale LANG=en_US.UTF-8
echo
echo -e "${VIOLET}\nБыла установлена кодировка UTF-8 для консоли.${WHITE}${RED} Надо перезагрузить сервер.${WHITE} "
tet=$(pwd)
echo -e "После перезагрузки запустите скрипт заново командой ${GREEN}${tet}/ri.sh${WHITE}"
Down
echo "Перезагрузить сервер?"
if vertical_menu "current" 2 0 5 "Да" "Нет"; then
echo "Перезагрузка сервера начата..."
reboot
else
RemoveRim
echo -e "Перезагрузите сервер самостоятельно командой ${GREEN}reboot${WHITE}"
exit 0
fi
fi
mark_step_completed "$STEP"
fi
STEP="Проверка и отключение SELinux если понадобится"
if ! check_step "$STEP"; then
if command -v sestatus >/dev/null 2>&1; then
SELINUX_STATE=$(getenforce)
if [ "$SELINUX_STATE" == "Enforcing" ] || [ "$SELINUX_STATE" == "Permissive" ]; then
echo "SELinux is enabled"
sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
echo
echo -e "Включен ${RED}selinux${WHITE}."
echo "Мы установили значение в конфигурационном файле для отключения selinux"
echo "Вам остается только выполнить перезагрузку сервера."
tet=$(pwd)
Down
echo -e "После перезагрузки запустите скрипт заново командой ${GREEN}${tet}/ri.sh${WHITE}"
echo "Перезагрузить сервер?"
if vertical_menu "current" 2 0 5 "Да" "Нет"; then
echo "Перезагрузка сервера начата..."
reboot
else
RemoveRim
echo -e "Перезагрузите сервер самостоятельно командой ${GREEN}reboot${WHITE}"
echo -e "После перезагрузки запустите скрипт заново командой ${GREEN}${tet}/ri.sh${WHITE}"
exit 0
fi
fi
fi
mark_step_completed "$STEP"
fi
STEP="Проверка и включение swap файла, если нужно"
if ! check_step "$STEP"; then
Down
create_swapfile
Up
mark_step_completed "$STEP"
fi
STEP="Выбор типа установки сервера"
Down
if ! check_step "$STEP"; then
echo -e "Начать ${GREEN}установку${WHITE} сервера?"
LocalServer=false
vertical_menu "current" 2 0 5 "Установка боевого (production) сервера" "Установка локального сервера" "Выйти"
ret=$?
if ((ret > 1)); then
RemoveRim
echo -e "${RED}Установка сервера прервана${WHITE}"
exit
fi
if ((ret == 1)); then
LocalServer=true
add_var_if_not_exists "LocalServer" "LocalServer=true"
Up
echo -e "Установка ${VIOLET}локального${WHITE} сервера"
Down
else
Up
echo -e "Установка ${RED}боевого${WHITE} сервера"
add_var_if_not_exists "LocalServer" "LocalServer=false"
Down
fi
mark_step_completed "$STEP"
else
source $config_file
fi
STEP="Установка mc, cronie, logrotate, idn2, epel-release, wget, tar"
if ! check_step "$STEP"; then
Install mc
Install cronie
Install logrotate
Install idn2
if ! echo ${CURRENT_OS} | egrep -q "Fedora"; then
Install epel-release
fi
Install wget
Install tar
mark_step_completed "$STEP"
fi
STEP="Установка telnet"
if ! check_step "$STEP"; then
if ${LocalServer}; then
Install "telnet"
fi
mark_step_completed "$STEP"
fi
STEP="Установка httpd mod_ssl"
if ! check_step "$STEP"; then
Install "httpd mod_ssl"
Up
httpd -v
echo
Down
mark_step_completed "$STEP"
fi
Down
STEP="Настройка файла ssl.conf для включения по умолчанию http/2"
if ! check_step "$STEP"; then
sed -i "/^Protocols .*$/d" /etc/httpd/conf.d/ssl.conf
sed -i "s|Listen 443 https.*$|Listen 443 https\nProtocols h2 http/1.1|" /etc/httpd/conf.d/ssl.conf
mark_step_completed "$STEP"
fi
STEP="Настройка автозапуска httpd при перезагрузке. Запуск httpd сейчас."
if ! check_step "$STEP"; then
systemctl enable httpd
echo
systemctl start httpd
echo
mark_step_completed "$STEP"
fi
STEP="Удаление файла autoindex для httpd"
if ! check_step "$STEP"; then
rm -f /etc/httpd/conf.d/autoindex.conf
mark_step_completed "$STEP"
fi
Up
STEP="Открытие портов 80 и 443 для web"
if ! check_step "$STEP"; then
OpenFirewall
mark_step_completed "$STEP"
fi
STEP="Закрытие портов cockpit"
if ! check_step "$STEP"; then
if ! ${LocalServer}; then
Down
echo -e "Закрываем порт доступа ${GREEN}cockpit${WHITE}?"
echo "Если не знаете что это такое - закрывайте"
if vertical_menu "current" 2 0 5 "Да" "Нет"; then
firewall-cmd --zone="${ZoneName}" --remove-service=cockpit --permanent
firewall-cmd --reload
fi
Up
fi
mark_step_completed "$STEP"
fi
STEP="Отключение heartbeat module apache"
if ! check_step "$STEP"; then
echo -e "Отключаем heartbeat module и перезапускаем ${GREEN}apache${WHITE}"
sed -i "s/LoadModule lbmethod_heartbeat_module/#LoadModule lbmethod_heartbeat_module/" /etc/httpd/conf.modules.d/00-proxy.conf
sed -i "s/##/#/" /etc/httpd/conf.modules.d/00-proxy.conf
mark_step_completed "$STEP"
fi
STEP="Замена стандартной заглушки Alma на заглушку RISH"
if ! check_step "$STEP"; then
rm -f /usr/share/httpd/noindex/index.html &>>$LOG_FILE
cp ${RISH_HOME}/index.html /usr/share/httpd/noindex/index.html &>>$LOG_FILE
mark_step_completed "$STEP"
fi
STEP="Проверка на наличие ServerName и исправление если его нет."
if ! check_step "$STEP"; then
if systemctl status httpd.service -l --no-pager -n 3 | grep "Could not"; then
echo "Устанавливаем имя сервера как localhost"
sed -i "s|#ServerName .*$|ServerName localhost|" /etc/httpd/conf/httpd.conf
systemctl restart httpd.service
fi
mark_step_completed "$STEP"
fi
STEP="Перезапуск httpd"
if ! check_step "$STEP"; then
Down
apachectl restart
Up
mark_step_completed "$STEP"
fi
STEP="Установка htop"
if ! check_step "$STEP"; then
Install "htop"
mark_step_completed "$STEP"
fi
STEP="Настройка репозиториев для установки php"
if ! check_step "$STEP"; then
echo -e "Ставим репозиторий ${GREEN}Remi Collet${WHITE} для установки ${GREEN}PHP${WHITE}"
Down
if echo ${CURRENT_OS} | egrep -q "Fedora"; then
FedoraVersion=$(cat /etc/fedora-release | sed 's@^[^0-9]*\([0-9]\+\).*@\1@')
dnf install -y https://rpms.remirepo.net/fedora/remi-release-${FedoraVersion}.rpm
dnf config-manager --set-enabled remi
else
if ! dnf install -y https://rpms.remirepo.net/enterprise/remi-release-${OS_VERSION}.rpm
then
echo -e "${RED}Ошибка${WHITE} при попытке установить репозитарий ${GREEN}Remi Collet${WHITE} для установки ${GREEN}PHP${WHITE}"
exit 1
fi
fi
Up
mark_step_completed "$STEP"
fi
STEP="Установка php"
if ! check_step "$STEP"; then
echo -e "Выбор и установка нужных версий ${GREEN}PHP${WHITE}"
Down
echo -e "Идет получение списка доступных версий ${GREEN}PHP${WHITE}. Ждите."
php_multi_install
Up
mark_step_completed "$STEP"
echo -e "Установка выбранных версий ${GREEN}PHP${WHITE} завершена."
fi
Down
STEP="Настройка файлов logrotate для httpd."
if ! check_step "$STEP"; then
sed -i "s/^#compress/compress/" /etc/logrotate.conf
if ! grep -q "daily" /etc/logrotate.d/httpd; then
sed -i "s/missingok/missingok\n daily/" /etc/logrotate.d/httpd
fi
if ! grep -q "/var/www/*/logs/*log" /etc/logrotate.d/httpd; then
echo "/var/www/*/logs/*log {" >>/etc/logrotate.d/httpd
echo " missingok" >>/etc/logrotate.d/httpd
echo " daily" >>/etc/logrotate.d/httpd
echo " maxsize 50M" >>/etc/logrotate.d/httpd
echo " notifempty" >>/etc/logrotate.d/httpd
echo " sharedscripts" >>/etc/logrotate.d/httpd
echo " delaycompress" >>/etc/logrotate.d/httpd
echo " postrotate" >>/etc/logrotate.d/httpd
echo " /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true" >>/etc/logrotate.d/httpd
echo " endscript" >>/etc/logrotate.d/httpd
echo "}" >>/etc/logrotate.d/httpd
fi
mark_step_completed "$STEP"
fi
STEP="Установка часового пояса для Москвы."
if ! check_step "$STEP"; then
Up
echo -e "Устанавливаем ${GREEN}время${WHITE}:"
Down
echo -e "Ставим ${GREEN}Московское время${WHITE}?"
if vertical_menu "current" 2 0 5 "Да" "Нет"; then
mv /etc/localtime /etc/localtime.bak
ln -s /usr/share/zoneinfo/Europe/Moscow /etc/localtime
fi
Up
date
Down
mark_step_completed "$STEP"
fi
STEP="Установка unzip"
if ! check_step "$STEP"; then
Install unzip
mark_step_completed "$STEP"
fi
STEP="Установка dnf-utils"
if ! check_step "$STEP"; then
Install dnf-utils
mark_step_completed "$STEP"
fi
STEP="Создание самоподписанного сертификата SSL на 10 лет"
if ! check_step "$STEP"; then
Up
echo -e "Генерируем ${GREEN}самоподписанный сертификат${WHITE} SSL на 10 лет"
Down
openssl req -new -days 3650 -x509 \
-subj "/C=RU/ST=Moscow/L=Springfield/O=Dis/CN=www.example.com" \
-nodes -out /etc/pki/tls/certs/localhost.crt \
-keyout /etc/pki/tls/private/localhost.key
mark_step_completed "$STEP"
fi
STEP="Создание хоста для ответа на обращения к несуществующим сайтам."
if ! check_step "$STEP"; then
cd /var/www/html
Up
echo -e "Создаем хост для ответа сервера на обращения к ${GREEN}несуществующим сайтам${WHITE} 000-default"
Down
if [[ ! -d 000-default ]]; then
mkdir 000-default
else
echo -e "каталог ${GREEN}000-default${WHITE} уже создан"
fi
cd /etc/httpd/conf.d
{
echo "<VirtualHost *:80>"
echo "ServerAdmin webmaster@localhost"
echo "ServerName 000-default"
echo "ServerAlias www.000-default"
echo "DocumentRoot /var/www/html/000-default"
echo "<Directory /var/www/html/000-default>"
echo " Options -Indexes +FollowSymLinks"
echo " AllowOverride All"
echo " Order allow,deny"
echo " allow from all"
echo "</Directory>"
echo "ServerSignature Off"
echo "ErrorLog /var/log/httpd/000-default-error-log"
echo "LogLevel warn"
echo "CustomLog /var/log/httpd/000-default-access-log combined"
echo "</VirtualHost>"
} >000-default.conf
{
echo "<VirtualHost *:443>"
echo "ServerAdmin webmaster@localhost"
echo "ServerName 000-default"
echo "ServerAlias www.000-default"
echo "DocumentRoot /var/www/html/000-default"
echo "<Directory /var/www/html/000-default>"
echo " Options -Indexes +FollowSymLinks"
echo " AllowOverride All"
echo " Order allow,deny"
echo " allow from all"
echo " deny from all"
echo "</Directory>"
echo "ServerSignature Off"
echo "ErrorLog /var/log/httpd/000-default-error-log"
echo "LogLevel warn"
echo "CustomLog /var/log/httpd/000-default-access-log combined"
echo "SSLCertificateFile /etc/pki/tls/certs/localhost.crt"
echo "SSLCertificateKeyFile /etc/pki/tls/private/localhost.key"
echo "</VirtualHost>"
} >000-default-ssl.conf
apachectl restart || {
echo "Ошибка при перезапуске Apache. Скрипт остановлен."
RemoveRim
exit 1
}
mark_step_completed "$STEP"
fi
pass=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 16 | xargs)
MYSQLPASS=${pass}
STEP="Установка mcedit как основного редактора"
if ! check_step "$STEP"; then
cd ~
if ! grep -q "EDITOR" ~/.bashrc; then
echo "export EDITOR=mcedit" >>~/.bashrc
fi
mark_step_completed "$STEP"
fi
STEP="Установка репозиториев для MariaDB"
if ! check_step "$STEP"; then
Up
echo
echo -e "Установка и настройка репозиториев для ${GREEN}MariaDB${WHITE}."
Down
cd /etc/yum.repos.d/
echo
echo -e "${GREEN}MariaDB${WHITE} на данный момент имеет два релиза с долгосрочной поддержкой:"
echo "10.6 со сроком поддержки до 6 июля 2026"
echo "10.11 со сроком поддержки до 16 февраля 2028"
echo -e "${GREEN}11.4${WHITE} со сроком поддержки до 29 мая 2029"
echo
echo "Какой релиз ставить?"
vertical_menu "current" 2 0 5 "MariaDB 11.4" "MariaDB 10.11" "MariaDB 10.6"
choice=$?
case "$choice" in
0)
Maria_Version="11.4"
;;
1)
Maria_Version="10.11"
;;
2)
Maria_Version="10.6"
;;
esac
echo -e "Выбрана версия ${GREEN}${Maria_Version}${WHITE}"
if ! bash /root/rish/mariadb_repo_setup.sh --mariadb-server-version=${Maria_Version}
then
{
echo "[mariadb]"
echo "name = MariaDB"
echo "# rpm.mariadb.org is a dynamic mirror if your preferred mirror goes offline. See https://mariadb.org/mirrorbits/ for details."
echo "# baseurl = https://rpm.mariadb.org/${Maria_Version}/rhel/\$releasever/\$basearch"
echo "baseurl = https://mirror.docker.ru/mariadb/yum/${Maria_Version}/rhel/\$releasever/\$basearch"
echo "module_hotfixes = 1"
echo "# gpgkey = https://rpm.mariadb.org/RPM-GPG-KEY-MariaDB"
echo "gpgkey = https://mirror.docker.ru/mariadb/yum/RPM-GPG-KEY-MariaDB"
echo "gpgcheck = 1"
} >mariadb.repo
fi
mark_step_completed "$STEP"
fi
STEP="Установка MariaDB"
if ! check_step "$STEP"; then
Up
echo
echo -e "Установка ${GREEN}MariaDB${WHITE} в качестве базы данных."
Down
mariadb_install
mark_step_completed "$STEP"
fi
STEP="Установка certbot"
if ! check_step "$STEP"; then
Up
echo
Down
echo -e "Ставим ${GREEN}certbot${WHITE} для получения SSL сертификатов?"
if vertical_menu "current" 2 0 5 "Да" "Нет"; then
Install "certbot python3-certbot-apache"
echo "───────────────────────────────────────"
echo -e "${GREEN}Настроим certbot.${WHITE} Введите свой ${GREEN}Email${WHITE} для обратной связи."
echo -e "На этот Email будут приходить сообщения о проблемах с сертификатами."
echo -e "Обязательно укажите корректный email."
echo -e "${GREEN}В конце сертификат для 000-default получать не нужно - просто нажмите 'c'${WHITE}"
echo "───────────────────────────────────────"
certbot --apache
fi
mark_step_completed "$STEP"
fi
STEP="Отключить почтовую службу"
if ! check_step "$STEP"; then
Up
echo "Если есть почтовая служба - отключаем и останавливаем"
Down
if systemctl status postfix; then
systemctl stop postfix
systemctl disable postfix
systemctl status postfix
Up
echo -e "${GREEN}Почтовая служба остановлена.${WHITE}"
Down
fi
mark_step_completed "$STEP"
fi
STEP="Делаем сервис apache автоматически перезапускаемым, в случае какого либо падения."
if ! check_step "$STEP"; then
Up
echo
echo "Делаем сервис apache автоматически перезапускаемым, в случае какого либо падения."
echo "Сервер будет пытаться перезапустить apache каждые 3 минуты в случае падения."
Down
if [[ ! -d /etc/systemd/system/httpd.service.d ]]; then
mkdir /etc/systemd/system/httpd.service.d
fi
cat >/etc/systemd/system/httpd.service.d/local.conf <<EOF
[Service]
Restart=always
RestartSec=180
EOF
Up
echo -e "Перезапускаем сервер ${GREEN}apache${WHITE} после настройки"
Down
systemctl daemon-reload
systemctl restart httpd
mark_step_completed "$STEP"
fi
STEP="Делаем сервис базы данных автоматически запускаемым, в случае какого либо падения"
if ! check_step "$STEP"; then
Up
echo
echo "Делаем сервис базы данных автоматически запускаемым, в случае какого либо падения."
echo "Сервер будет пытаться перезапустить базу каждые 3 минуты в случае падения."
Down