-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathmarzban.sh
More file actions
executable file
·1592 lines (1357 loc) · 50.8 KB
/
marzban.sh
File metadata and controls
executable file
·1592 lines (1357 loc) · 50.8 KB
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 -e
INSTALL_DIR="/opt"
if [ -z "$APP_NAME" ]; then
APP_NAME="marzban"
fi
APP_DIR="$INSTALL_DIR/$APP_NAME"
DATA_DIR="/var/lib/$APP_NAME"
COMPOSE_FILE="$APP_DIR/docker-compose.yml"
ENV_FILE="$APP_DIR/.env"
LAST_XRAY_CORES=10
colorized_echo() {
local color=$1
local text=$2
case $color in
"red")
printf "\e[91m${text}\e[0m\n";;
"green")
printf "\e[92m${text}\e[0m\n";;
"yellow")
printf "\e[93m${text}\e[0m\n";;
"blue")
printf "\e[94m${text}\e[0m\n";;
"magenta")
printf "\e[95m${text}\e[0m\n";;
"cyan")
printf "\e[96m${text}\e[0m\n";;
*)
echo "${text}"
;;
esac
}
check_running_as_root() {
if [ "$(id -u)" != "0" ]; then
colorized_echo red "This command must be run as root."
exit 1
fi
}
detect_os() {
# Detect the operating system
if [ -f /etc/lsb-release ]; then
OS=$(lsb_release -si)
elif [ -f /etc/os-release ]; then
OS=$(awk -F= '/^NAME/{print $2}' /etc/os-release | tr -d '"')
elif [ -f /etc/redhat-release ]; then
OS=$(cat /etc/redhat-release | awk '{print $1}')
elif [ -f /etc/arch-release ]; then
OS="Arch"
else
colorized_echo red "Unsupported operating system"
exit 1
fi
}
detect_and_update_package_manager() {
colorized_echo blue "Updating package manager"
if [[ "$OS" == "Ubuntu"* ]] || [[ "$OS" == "Debian"* ]]; then
PKG_MANAGER="apt-get"
$PKG_MANAGER update
elif [[ "$OS" == "CentOS"* ]] || [[ "$OS" == "AlmaLinux"* ]]; then
PKG_MANAGER="yum"
$PKG_MANAGER update -y
$PKG_MANAGER install -y epel-release
elif [ "$OS" == "Fedora"* ]; then
PKG_MANAGER="dnf"
$PKG_MANAGER update
elif [ "$OS" == "Arch" ]; then
PKG_MANAGER="pacman"
$PKG_MANAGER -Sy
elif [[ "$OS" == "openSUSE"* ]]; then
PKG_MANAGER="zypper"
$PKG_MANAGER refresh
else
colorized_echo red "Unsupported operating system"
exit 1
fi
}
install_package () {
if [ -z $PKG_MANAGER ]; then
detect_and_update_package_manager
fi
PACKAGE=$1
colorized_echo blue "Installing $PACKAGE"
if [[ "$OS" == "Ubuntu"* ]] || [[ "$OS" == "Debian"* ]]; then
$PKG_MANAGER -y install "$PACKAGE"
elif [[ "$OS" == "CentOS"* ]] || [[ "$OS" == "AlmaLinux"* ]]; then
$PKG_MANAGER install -y "$PACKAGE"
elif [ "$OS" == "Fedora"* ]; then
$PKG_MANAGER install -y "$PACKAGE"
elif [ "$OS" == "Arch" ]; then
$PKG_MANAGER -S --noconfirm "$PACKAGE"
else
colorized_echo red "Unsupported operating system"
exit 1
fi
}
install_docker() {
# Install Docker and Docker Compose using the official installation script
colorized_echo blue "Installing Docker"
curl -fsSL https://get.docker.com | sh
colorized_echo green "Docker installed successfully"
}
detect_compose() {
# Check if docker compose command exists
if docker compose version >/dev/null 2>&1; then
COMPOSE='docker compose'
elif docker-compose version >/dev/null 2>&1; then
COMPOSE='docker-compose'
else
colorized_echo red "docker compose not found"
exit 1
fi
}
install_marzban_script() {
FETCH_REPO="Gozargah/Marzban-scripts"
SCRIPT_URL="https://github.com/$FETCH_REPO/raw/master/marzban.sh"
colorized_echo blue "Installing marzban script"
curl -sSL $SCRIPT_URL | install -m 755 /dev/stdin /usr/local/bin/marzban
colorized_echo green "marzban script installed successfully"
}
is_marzban_installed() {
if [ -d $APP_DIR ]; then
return 0
else
return 1
fi
}
identify_the_operating_system_and_architecture() {
if [[ "$(uname)" == 'Linux' ]]; then
case "$(uname -m)" in
'i386' | 'i686')
ARCH='32'
;;
'amd64' | 'x86_64')
ARCH='64'
;;
'armv5tel')
ARCH='arm32-v5'
;;
'armv6l')
ARCH='arm32-v6'
grep Features /proc/cpuinfo | grep -qw 'vfp' || ARCH='arm32-v5'
;;
'armv7' | 'armv7l')
ARCH='arm32-v7a'
grep Features /proc/cpuinfo | grep -qw 'vfp' || ARCH='arm32-v5'
;;
'armv8' | 'aarch64')
ARCH='arm64-v8a'
;;
'mips')
ARCH='mips32'
;;
'mipsle')
ARCH='mips32le'
;;
'mips64')
ARCH='mips64'
lscpu | grep -q "Little Endian" && ARCH='mips64le'
;;
'mips64le')
ARCH='mips64le'
;;
'ppc64')
ARCH='ppc64'
;;
'ppc64le')
ARCH='ppc64le'
;;
'riscv64')
ARCH='riscv64'
;;
's390x')
ARCH='s390x'
;;
*)
echo "error: The architecture is not supported."
exit 1
;;
esac
else
echo "error: This operating system is not supported."
exit 1
fi
}
send_backup_to_telegram() {
if [ -f "$ENV_FILE" ]; then
while IFS='=' read -r key value; do
if [[ -z "$key" || "$key" =~ ^# ]]; then
continue
fi
key=$(echo "$key" | xargs)
value=$(echo "$value" | xargs)
if [[ "$key" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
export "$key"="$value"
else
colorized_echo yellow "Skipping invalid line in .env: $key=$value"
fi
done < "$ENV_FILE"
else
colorized_echo red "Environment file (.env) not found."
exit 1
fi
if [ "$BACKUP_SERVICE_ENABLED" != "true" ]; then
colorized_echo yellow "Backup service is not enabled. Skipping Telegram upload."
return
fi
local server_ip=$(curl -s ifconfig.me || echo "Unknown IP")
local latest_backup=$(ls -t "$APP_DIR/backup" | head -n 1)
local backup_path="$APP_DIR/backup/$latest_backup"
if [ ! -f "$backup_path" ]; then
colorized_echo red "No backups found to send."
return
fi
local backup_size=$(du -m "$backup_path" | cut -f1)
local split_dir="/tmp/marzban_backup_split"
local is_single_file=true
mkdir -p "$split_dir"
if [ "$backup_size" -gt 49 ]; then
colorized_echo yellow "Backup is larger than 49MB. Splitting the archive..."
split -b 49M "$backup_path" "$split_dir/part_"
is_single_file=false
else
cp "$backup_path" "$split_dir/part_aa"
fi
local backup_time=$(date "+%Y-%m-%d %H:%M:%S %Z")
for part in "$split_dir"/*; do
local part_name=$(basename "$part")
local custom_filename="backup_${part_name}.tar.gz"
local caption="📦 *Backup Information*\n🌐 *Server IP*: \`${server_ip}\`\n📁 *Backup File*: \`${custom_filename}\`\n⏰ *Backup Time*: \`${backup_time}\`"
curl -s -F chat_id="$BACKUP_TELEGRAM_CHAT_ID" \
-F document=@"$part;filename=$custom_filename" \
-F caption="$(echo -e "$caption" | sed 's/-/\\-/g;s/\./\\./g;s/_/\\_/g')" \
-F parse_mode="MarkdownV2" \
"https://api.telegram.org/bot$BACKUP_TELEGRAM_BOT_KEY/sendDocument" >/dev/null 2>&1 && \
colorized_echo green "Backup part $custom_filename successfully sent to Telegram." || \
colorized_echo red "Failed to send backup part $custom_filename to Telegram."
done
rm -rf "$split_dir"
}
send_backup_error_to_telegram() {
local error_messages=$1
local log_file=$2
local server_ip=$(curl -s ifconfig.me || echo "Unknown IP")
local error_time=$(date "+%Y-%m-%d %H:%M:%S %Z")
local message="⚠️ *Backup Error Notification*\n"
message+="🌐 *Server IP*: \`${server_ip}\`\n"
message+="❌ *Errors*:\n\`${error_messages//_/\\_}\`\n"
message+="⏰ *Time*: \`${error_time}\`"
message=$(echo -e "$message" | sed 's/-/\\-/g;s/\./\\./g;s/_/\\_/g;s/(/\\(/g;s/)/\\)/g')
local max_length=1000
if [ ${#message} -gt $max_length ]; then
message="${message:0:$((max_length - 50))}...\n\`[Message truncated]\`"
fi
curl -s -X POST "https://api.telegram.org/bot$BACKUP_TELEGRAM_BOT_KEY/sendMessage" \
-d chat_id="$BACKUP_TELEGRAM_CHAT_ID" \
-d parse_mode="MarkdownV2" \
-d text="$message" >/dev/null 2>&1 && \
colorized_echo green "Backup error notification sent to Telegram." || \
colorized_echo red "Failed to send error notification to Telegram."
if [ -f "$log_file" ]; then
response=$(curl -s -w "%{http_code}" -o /tmp/tg_response.json \
-F chat_id="$BACKUP_TELEGRAM_CHAT_ID" \
-F document=@"$log_file;filename=backup_error.log" \
-F caption="📜 *Backup Error Log* - ${error_time}" \
"https://api.telegram.org/bot$BACKUP_TELEGRAM_BOT_KEY/sendDocument")
http_code="${response:(-3)}"
if [ "$http_code" -eq 200 ]; then
colorized_echo green "Backup error log sent to Telegram."
else
colorized_echo red "Failed to send backup error log to Telegram. HTTP code: $http_code"
cat /tmp/tg_response.json
fi
else
colorized_echo red "Log file not found: $log_file"
fi
}
backup_service() {
local telegram_bot_key=""
local telegram_chat_id=""
local cron_schedule=""
local interval_hours=""
colorized_echo blue "====================================="
colorized_echo blue " Welcome to Backup Service "
colorized_echo blue "====================================="
if grep -q "BACKUP_SERVICE_ENABLED=true" "$ENV_FILE"; then
telegram_bot_key=$(awk -F'=' '/^BACKUP_TELEGRAM_BOT_KEY=/ {print $2}' "$ENV_FILE")
telegram_chat_id=$(awk -F'=' '/^BACKUP_TELEGRAM_CHAT_ID=/ {print $2}' "$ENV_FILE")
cron_schedule=$(awk -F'=' '/^BACKUP_CRON_SCHEDULE=/ {print $2}' "$ENV_FILE" | tr -d '"')
if [[ "$cron_schedule" == "0 0 * * *" ]]; then
interval_hours=24
else
interval_hours=$(echo "$cron_schedule" | grep -oP '(?<=\*/)[0-9]+')
fi
colorized_echo green "====================================="
colorized_echo green "Current Backup Configuration:"
colorized_echo cyan "Telegram Bot API Key: $telegram_bot_key"
colorized_echo cyan "Telegram Chat ID: $telegram_chat_id"
colorized_echo cyan "Backup Interval: Every $interval_hours hour(s)"
colorized_echo green "====================================="
echo "Choose an option:"
echo "1. Reconfigure Backup Service"
echo "2. Remove Backup Service"
echo "3. Exit"
read -p "Enter your choice (1-3): " user_choice
case $user_choice in
1)
colorized_echo yellow "Starting reconfiguration..."
remove_backup_service
;;
2)
colorized_echo yellow "Removing Backup Service..."
remove_backup_service
return
;;
3)
colorized_echo yellow "Exiting..."
return
;;
*)
colorized_echo red "Invalid choice. Exiting."
return
;;
esac
else
colorized_echo yellow "No backup service is currently configured."
fi
while true; do
printf "Enter your Telegram bot API key: "
read telegram_bot_key
if [[ -n "$telegram_bot_key" ]]; then
break
else
colorized_echo red "API key cannot be empty. Please try again."
fi
done
while true; do
printf "Enter your Telegram chat ID: "
read telegram_chat_id
if [[ -n "$telegram_chat_id" ]]; then
break
else
colorized_echo red "Chat ID cannot be empty. Please try again."
fi
done
while true; do
printf "Set up the backup interval in hours (1-24):\n"
read interval_hours
if ! [[ "$interval_hours" =~ ^[0-9]+$ ]]; then
colorized_echo red "Invalid input. Please enter a valid number."
continue
fi
if [[ "$interval_hours" -eq 24 ]]; then
cron_schedule="0 0 * * *"
colorized_echo green "Setting backup to run daily at midnight."
break
fi
if [[ "$interval_hours" -ge 1 && "$interval_hours" -le 23 ]]; then
cron_schedule="0 */$interval_hours * * *"
colorized_echo green "Setting backup to run every $interval_hours hour(s)."
break
else
colorized_echo red "Invalid input. Please enter a number between 1-24."
fi
done
sed -i '/^BACKUP_SERVICE_ENABLED/d' "$ENV_FILE"
sed -i '/^BACKUP_TELEGRAM_BOT_KEY/d' "$ENV_FILE"
sed -i '/^BACKUP_TELEGRAM_CHAT_ID/d' "$ENV_FILE"
sed -i '/^BACKUP_CRON_SCHEDULE/d' "$ENV_FILE"
{
echo ""
echo "# Backup service configuration"
echo "BACKUP_SERVICE_ENABLED=true"
echo "BACKUP_TELEGRAM_BOT_KEY=$telegram_bot_key"
echo "BACKUP_TELEGRAM_CHAT_ID=$telegram_chat_id"
echo "BACKUP_CRON_SCHEDULE=\"$cron_schedule\""
} >> "$ENV_FILE"
colorized_echo green "Backup service configuration saved in $ENV_FILE."
local backup_command="$(which bash) -c '$APP_NAME backup'"
add_cron_job "$cron_schedule" "$backup_command"
colorized_echo green "Backup service successfully configured."
if [[ "$interval_hours" -eq 24 ]]; then
colorized_echo cyan "Backups will be sent to Telegram daily (every 24 hours at midnight)."
else
colorized_echo cyan "Backups will be sent to Telegram every $interval_hours hour(s)."
fi
colorized_echo green "====================================="
}
add_cron_job() {
local schedule="$1"
local command="$2"
local temp_cron=$(mktemp)
crontab -l 2>/dev/null > "$temp_cron" || true
grep -v "$command" "$temp_cron" > "${temp_cron}.tmp" && mv "${temp_cron}.tmp" "$temp_cron"
echo "$schedule $command # marzban-backup-service" >> "$temp_cron"
if crontab "$temp_cron"; then
colorized_echo green "Cron job successfully added."
else
colorized_echo red "Failed to add cron job. Please check manually."
fi
rm -f "$temp_cron"
}
remove_backup_service() {
colorized_echo red "in process..."
sed -i '/^# Backup service configuration/d' "$ENV_FILE"
sed -i '/BACKUP_SERVICE_ENABLED/d' "$ENV_FILE"
sed -i '/BACKUP_TELEGRAM_BOT_KEY/d' "$ENV_FILE"
sed -i '/BACKUP_TELEGRAM_CHAT_ID/d' "$ENV_FILE"
sed -i '/BACKUP_CRON_SCHEDULE/d' "$ENV_FILE"
local temp_cron=$(mktemp)
crontab -l 2>/dev/null > "$temp_cron"
sed -i '/# marzban-backup-service/d' "$temp_cron"
if crontab "$temp_cron"; then
colorized_echo green "Backup service task removed from crontab."
else
colorized_echo red "Failed to update crontab. Please check manually."
fi
rm -f "$temp_cron"
colorized_echo green "Backup service has been removed."
}
backup_command() {
local backup_dir="$APP_DIR/backup"
local temp_dir="/tmp/marzban_backup"
local timestamp=$(date +"%Y%m%d%H%M%S")
local backup_file="$backup_dir/backup_$timestamp.tar.gz"
local error_messages=()
local log_file="/var/log/marzban_backup_error.log"
> "$log_file"
echo "Backup Log - $(date)" > "$log_file"
if ! command -v rsync >/dev/null 2>&1; then
detect_os
install_package rsync
fi
rm -rf "$backup_dir"
mkdir -p "$backup_dir"
mkdir -p "$temp_dir"
if [ -f "$ENV_FILE" ]; then
while IFS='=' read -r key value; do
if [[ -z "$key" || "$key" =~ ^# ]]; then
continue
fi
key=$(echo "$key" | xargs)
value=$(echo "$value" | xargs)
if [[ "$key" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
export "$key"="$value"
else
echo "Skipping invalid line in .env: $key=$value" >> "$log_file"
fi
done < "$ENV_FILE"
else
error_messages+=("Environment file (.env) not found.")
echo "Environment file (.env) not found." >> "$log_file"
send_backup_error_to_telegram "${error_messages[*]}" "$log_file"
exit 1
fi
local db_type=""
local sqlite_file=""
if grep -q "image: mariadb" "$COMPOSE_FILE"; then
db_type="mariadb"
container_name=$(docker compose -f "$COMPOSE_FILE" ps -q mariadb || echo "mariadb")
elif grep -q "image: mysql" "$COMPOSE_FILE"; then
db_type="mysql"
container_name=$(docker compose -f "$COMPOSE_FILE" ps -q mysql || echo "mysql")
elif grep -q "SQLALCHEMY_DATABASE_URL = .*sqlite" "$ENV_FILE"; then
db_type="sqlite"
sqlite_file=$(grep -Po '(?<=SQLALCHEMY_DATABASE_URL = "sqlite:////).*"' "$ENV_FILE" | tr -d '"')
if [[ ! "$sqlite_file" =~ ^/ ]]; then
sqlite_file="/$sqlite_file"
fi
fi
if [ -n "$db_type" ]; then
echo "Database detected: $db_type" >> "$log_file"
case $db_type in
mariadb)
if ! docker exec "$container_name" mariadb-dump -u root -p"$MYSQL_ROOT_PASSWORD" --all-databases --ignore-database=mysql --ignore-database=performance_schema --ignore-database=information_schema --ignore-database=sys --events --triggers > "$temp_dir/db_backup.sql" 2>>"$log_file"; then
error_messages+=("MariaDB dump failed.")
fi
;;
mysql)
if ! docker exec "$container_name" mysqldump -u root -p"$MYSQL_ROOT_PASSWORD" marzban --events --triggers > "$temp_dir/db_backup.sql" 2>>"$log_file"; then
error_messages+=("MySQL dump failed.")
fi
;;
sqlite)
if [ -f "$sqlite_file" ]; then
if ! cp "$sqlite_file" "$temp_dir/db_backup.sqlite" 2>>"$log_file"; then
error_messages+=("Failed to copy SQLite database.")
fi
else
error_messages+=("SQLite database file not found at $sqlite_file.")
fi
;;
esac
fi
cp "$APP_DIR/.env" "$temp_dir/" 2>>"$log_file"
cp "$APP_DIR/docker-compose.yml" "$temp_dir/" 2>>"$log_file"
rsync -av --exclude 'xray-core' --exclude 'mysql' "$DATA_DIR/" "$temp_dir/marzban_data/" >>"$log_file" 2>&1
if ! tar -czf "$backup_file" -C "$temp_dir" .; then
error_messages+=("Failed to create backup archive.")
echo "Failed to create backup archive." >> "$log_file"
fi
rm -rf "$temp_dir"
if [ ${#error_messages[@]} -gt 0 ]; then
send_backup_error_to_telegram "${error_messages[*]}" "$log_file"
return
fi
colorized_echo green "Backup created: $backup_file"
send_backup_to_telegram "$backup_file"
}
get_xray_core() {
identify_the_operating_system_and_architecture
clear
validate_version() {
local version="$1"
local response=$(curl -s "https://api.github.com/repos/XTLS/Xray-core/releases/tags/$version")
if echo "$response" | grep -q '"message": "Not Found"'; then
echo "invalid"
else
echo "valid"
fi
}
print_menu() {
clear
echo -e "\033[1;32m==============================\033[0m"
echo -e "\033[1;32m Xray-core Installer \033[0m"
echo -e "\033[1;32m==============================\033[0m"
echo -e "\033[1;33mAvailable Xray-core versions:\033[0m"
for ((i=0; i<${#versions[@]}; i++)); do
echo -e "\033[1;34m$((i + 1)):\033[0m ${versions[i]}"
done
echo -e "\033[1;32m==============================\033[0m"
echo -e "\033[1;35mM:\033[0m Enter a version manually"
echo -e "\033[1;31mQ:\033[0m Quit"
echo -e "\033[1;32m==============================\033[0m"
}
latest_releases=$(curl -s "https://api.github.com/repos/XTLS/Xray-core/releases?per_page=$LAST_XRAY_CORES")
versions=($(echo "$latest_releases" | grep -oP '"tag_name": "\K(.*?)(?=")'))
while true; do
print_menu
read -p "Choose a version to install (1-${#versions[@]}), or press M to enter manually, Q to quit: " choice
if [[ "$choice" =~ ^[1-9][0-9]*$ ]] && [ "$choice" -le "${#versions[@]}" ]; then
choice=$((choice - 1))
selected_version=${versions[choice]}
break
elif [ "$choice" == "M" ] || [ "$choice" == "m" ]; then
while true; do
read -p "Enter the version manually (e.g., v1.2.3): " custom_version
if [ "$(validate_version "$custom_version")" == "valid" ]; then
selected_version="$custom_version"
break 2
else
echo -e "\033[1;31mInvalid version or version does not exist. Please try again.\033[0m"
fi
done
elif [ "$choice" == "Q" ] || [ "$choice" == "q" ]; then
echo -e "\033[1;31mExiting.\033[0m"
exit 0
else
echo -e "\033[1;31mInvalid choice. Please try again.\033[0m"
sleep 2
fi
done
echo -e "\033[1;32mSelected version $selected_version for installation.\033[0m"
# Check if the required packages are installed
if ! command -v unzip >/dev/null 2>&1; then
echo -e "\033[1;33mInstalling required packages...\033[0m"
detect_os
install_package unzip
fi
if ! command -v wget >/dev/null 2>&1; then
echo -e "\033[1;33mInstalling required packages...\033[0m"
detect_os
install_package wget
fi
mkdir -p $DATA_DIR/xray-core
cd $DATA_DIR/xray-core
xray_filename="Xray-linux-$ARCH.zip"
xray_download_url="https://github.com/XTLS/Xray-core/releases/download/${selected_version}/${xray_filename}"
echo -e "\033[1;33mDownloading Xray-core version ${selected_version}...\033[0m"
wget -q -O "${xray_filename}" "${xray_download_url}"
echo -e "\033[1;33mExtracting Xray-core...\033[0m"
unzip -o "${xray_filename}" >/dev/null 2>&1
rm "${xray_filename}"
}
# Function to update the Marzban Main core
update_core_command() {
check_running_as_root
get_xray_core
# Change the Marzban core
xray_executable_path="XRAY_EXECUTABLE_PATH=\"/var/lib/marzban/xray-core/xray\""
echo "Changing the Marzban core..."
# Check if the XRAY_EXECUTABLE_PATH string already exists in the .env file
if ! grep -q "^XRAY_EXECUTABLE_PATH=" "$ENV_FILE"; then
# If the string does not exist, add it
echo "${xray_executable_path}" >> "$ENV_FILE"
else
# Update the existing XRAY_EXECUTABLE_PATH line
sed -i "s~^XRAY_EXECUTABLE_PATH=.*~${xray_executable_path}~" "$ENV_FILE"
fi
# Restart Marzban
colorized_echo red "Restarting Marzban..."
if restart_command -n >/dev/null 2>&1; then
colorized_echo green "Marzban successfully restarted!"
else
colorized_echo red "Marzban restart failed!"
fi
colorized_echo blue "Installation of Xray-core version $selected_version completed."
}
install_marzban() {
local marzban_version=$1
local database_type=$2
# Fetch releases
FILES_URL_PREFIX="https://raw.githubusercontent.com/Gozargah/Marzban/master"
mkdir -p "$DATA_DIR"
mkdir -p "$APP_DIR"
colorized_echo blue "Setting up docker-compose.yml"
docker_file_path="$APP_DIR/docker-compose.yml"
if [ "$database_type" == "mariadb" ]; then
# Generate docker-compose.yml with MariaDB content
cat > "$docker_file_path" <<EOF
services:
marzban:
image: gozargah/marzban:${marzban_version}
restart: always
env_file: .env
network_mode: host
volumes:
- /var/lib/marzban:/var/lib/marzban
- /var/lib/marzban/logs:/var/lib/marzban-node
depends_on:
mariadb:
condition: service_healthy
mariadb:
image: mariadb:lts
env_file: .env
network_mode: host
restart: always
environment:
MYSQL_ROOT_PASSWORD: \${MYSQL_ROOT_PASSWORD}
MYSQL_ROOT_HOST: '%'
MYSQL_DATABASE: \${MYSQL_DATABASE}
MYSQL_USER: \${MYSQL_USER}
MYSQL_PASSWORD: \${MYSQL_PASSWORD}
command:
- --bind-address=127.0.0.1 # Restricts access to localhost for increased security
- --character_set_server=utf8mb4 # Sets UTF-8 character set for full Unicode support
- --collation_server=utf8mb4_unicode_ci # Defines collation for Unicode
- --host-cache-size=0 # Disables host cache to prevent DNS issues
- --innodb-open-files=1024 # Sets the limit for InnoDB open files
- --innodb-buffer-pool-size=256M # Allocates buffer pool size for InnoDB
- --binlog_expire_logs_seconds=1209600 # Sets binary log expiration to 14 days (2 weeks)
- --innodb-log-file-size=64M # Sets InnoDB log file size to balance log retention and performance
- --innodb-log-files-in-group=2 # Uses two log files to balance recovery and disk I/O
- --innodb-doublewrite=0 # Disables doublewrite buffer (reduces disk I/O; may increase data loss risk)
- --general_log=0 # Disables general query log to reduce disk usage
- --slow_query_log=1 # Enables slow query log for identifying performance issues
- --slow_query_log_file=/var/lib/mysql/slow.log # Logs slow queries for troubleshooting
- --long_query_time=2 # Defines slow query threshold as 2 seconds
volumes:
- /var/lib/marzban/mysql:/var/lib/mysql
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
start_period: 10s
start_interval: 3s
interval: 10s
timeout: 5s
retries: 3
EOF
echo "----------------------------"
colorized_echo red "Using MariaDB as database"
echo "----------------------------"
colorized_echo green "File generated at $APP_DIR/docker-compose.yml"
# Modify .env file
colorized_echo blue "Fetching .env file"
curl -sL "$FILES_URL_PREFIX/.env.example" -o "$APP_DIR/.env"
# Comment out the SQLite line
sed -i 's~^\(SQLALCHEMY_DATABASE_URL = "sqlite:////var/lib/marzban/db.sqlite3"\)~#\1~' "$APP_DIR/.env"
# Add the MySQL connection string
#echo -e '\nSQLALCHEMY_DATABASE_URL = "mysql+pymysql://marzban:password@127.0.0.1:3306/marzban"' >> "$APP_DIR/.env"
sed -i 's/^# \(XRAY_JSON = .*\)$/\1/' "$APP_DIR/.env"
sed -i 's~\(XRAY_JSON = \).*~\1"/var/lib/marzban/xray_config.json"~' "$APP_DIR/.env"
prompt_for_marzban_password
MYSQL_ROOT_PASSWORD=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 20)
echo "" >> "$ENV_FILE"
echo "" >> "$ENV_FILE"
echo "# Database configuration" >> "$ENV_FILE"
echo "MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD" >> "$ENV_FILE"
echo "MYSQL_DATABASE=marzban" >> "$ENV_FILE"
echo "MYSQL_USER=marzban" >> "$ENV_FILE"
echo "MYSQL_PASSWORD=$MYSQL_PASSWORD" >> "$ENV_FILE"
SQLALCHEMY_DATABASE_URL="mysql+pymysql://marzban:${MYSQL_PASSWORD}@127.0.0.1:3306/marzban"
echo "" >> "$ENV_FILE"
echo "# SQLAlchemy Database URL" >> "$ENV_FILE"
echo "SQLALCHEMY_DATABASE_URL=\"$SQLALCHEMY_DATABASE_URL\"" >> "$ENV_FILE"
colorized_echo green "File saved in $APP_DIR/.env"
elif [ "$database_type" == "mysql" ]; then
# Generate docker-compose.yml with MySQL content
cat > "$docker_file_path" <<EOF
services:
marzban:
image: gozargah/marzban:${marzban_version}
restart: always
env_file: .env
network_mode: host
volumes:
- /var/lib/marzban:/var/lib/marzban
- /var/lib/marzban/logs:/var/lib/marzban-node
depends_on:
mysql:
condition: service_healthy
mysql:
image: mysql:lts
env_file: .env
network_mode: host
restart: always
environment:
MYSQL_ROOT_PASSWORD: \${MYSQL_ROOT_PASSWORD}
MYSQL_ROOT_HOST: '%'
MYSQL_DATABASE: \${MYSQL_DATABASE}
MYSQL_USER: \${MYSQL_USER}
MYSQL_PASSWORD: \${MYSQL_PASSWORD}
command:
- --mysqlx=OFF # Disables MySQL X Plugin to save resources if X Protocol isn't used
- --bind-address=127.0.0.1 # Restricts access to localhost for increased security
- --character_set_server=utf8mb4 # Sets UTF-8 character set for full Unicode support
- --collation_server=utf8mb4_unicode_ci # Defines collation for Unicode
- --log-bin=mysql-bin # Enables binary logging for point-in-time recovery
- --binlog_expire_logs_seconds=1209600 # Sets binary log expiration to 14 days
- --host-cache-size=0 # Disables host cache to prevent DNS issues
- --innodb-open-files=1024 # Sets the limit for InnoDB open files
- --innodb-buffer-pool-size=256M # Allocates buffer pool size for InnoDB
- --innodb-log-file-size=64M # Sets InnoDB log file size to balance log retention and performance
- --innodb-log-files-in-group=2 # Uses two log files to balance recovery and disk I/O
- --general_log=0 # Disables general query log for lower disk usage
- --slow_query_log=1 # Enables slow query log for performance analysis
- --slow_query_log_file=/var/lib/mysql/slow.log # Logs slow queries for troubleshooting
- --long_query_time=2 # Defines slow query threshold as 2 seconds
volumes:
- /var/lib/marzban/mysql:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "marzban", "--password=\${MYSQL_PASSWORD}"]
start_period: 5s
interval: 5s
timeout: 5s
retries: 55
EOF
echo "----------------------------"
colorized_echo red "Using MySQL as database"
echo "----------------------------"
colorized_echo green "File generated at $APP_DIR/docker-compose.yml"
# Modify .env file
colorized_echo blue "Fetching .env file"
curl -sL "$FILES_URL_PREFIX/.env.example" -o "$APP_DIR/.env"
# Comment out the SQLite line
sed -i 's~^\(SQLALCHEMY_DATABASE_URL = "sqlite:////var/lib/marzban/db.sqlite3"\)~#\1~' "$APP_DIR/.env"
# Add the MySQL connection string
#echo -e '\nSQLALCHEMY_DATABASE_URL = "mysql+pymysql://marzban:password@127.0.0.1:3306/marzban"' >> "$APP_DIR/.env"
sed -i 's/^# \(XRAY_JSON = .*\)$/\1/' "$APP_DIR/.env"
sed -i 's~\(XRAY_JSON = \).*~\1"/var/lib/marzban/xray_config.json"~' "$APP_DIR/.env"
prompt_for_marzban_password
MYSQL_ROOT_PASSWORD=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 20)
echo "" >> "$ENV_FILE"
echo "" >> "$ENV_FILE"
echo "# Database configuration" >> "$ENV_FILE"
echo "MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD" >> "$ENV_FILE"
echo "MYSQL_DATABASE=marzban" >> "$ENV_FILE"
echo "MYSQL_USER=marzban" >> "$ENV_FILE"
echo "MYSQL_PASSWORD=$MYSQL_PASSWORD" >> "$ENV_FILE"
SQLALCHEMY_DATABASE_URL="mysql+pymysql://marzban:${MYSQL_PASSWORD}@127.0.0.1:3306/marzban"
echo "" >> "$ENV_FILE"
echo "# SQLAlchemy Database URL" >> "$ENV_FILE"
echo "SQLALCHEMY_DATABASE_URL=\"$SQLALCHEMY_DATABASE_URL\"" >> "$ENV_FILE"
colorized_echo green "File saved in $APP_DIR/.env"
else
echo "----------------------------"
colorized_echo red "Using SQLite as database"
echo "----------------------------"
colorized_echo blue "Fetching compose file"
curl -sL "$FILES_URL_PREFIX/docker-compose.yml" -o "$docker_file_path"
# Install requested version
if [ "$marzban_version" == "latest" ]; then
yq -i '.services.marzban.image = "gozargah/marzban:latest"' "$docker_file_path"
else
yq -i ".services.marzban.image = \"gozargah/marzban:${marzban_version}\"" "$docker_file_path"
fi
echo "Installing $marzban_version version"
colorized_echo green "File saved in $APP_DIR/docker-compose.yml"
colorized_echo blue "Fetching .env file"
curl -sL "$FILES_URL_PREFIX/.env.example" -o "$APP_DIR/.env"
sed -i 's/^# \(XRAY_JSON = .*\)$/\1/' "$APP_DIR/.env"
sed -i 's/^# \(SQLALCHEMY_DATABASE_URL = .*\)$/\1/' "$APP_DIR/.env"
sed -i 's~\(XRAY_JSON = \).*~\1"/var/lib/marzban/xray_config.json"~' "$APP_DIR/.env"
sed -i 's~\(SQLALCHEMY_DATABASE_URL = \).*~\1"sqlite:////var/lib/marzban/db.sqlite3"~' "$APP_DIR/.env"
colorized_echo green "File saved in $APP_DIR/.env"
fi
colorized_echo blue "Fetching xray config file"
curl -sL "$FILES_URL_PREFIX/xray_config.json" -o "$DATA_DIR/xray_config.json"
colorized_echo green "File saved in $DATA_DIR/xray_config.json"
colorized_echo green "Marzban's files downloaded successfully"
}
up_marzban() {
$COMPOSE -f $COMPOSE_FILE -p "$APP_NAME" up -d --remove-orphans
}
follow_marzban_logs() {
$COMPOSE -f $COMPOSE_FILE -p "$APP_NAME" logs -f
}
status_command() {
# Check if marzban is installed
if ! is_marzban_installed; then
echo -n "Status: "
colorized_echo red "Not Installed"
exit 1
fi
detect_compose
if ! is_marzban_up; then
echo -n "Status: "
colorized_echo blue "Down"
exit 1
fi
echo -n "Status: "
colorized_echo green "Up"
json=$($COMPOSE -f $COMPOSE_FILE ps -a --format=json)
services=$(echo "$json" | jq -r 'if type == "array" then .[] else . end | .Service')
states=$(echo "$json" | jq -r 'if type == "array" then .[] else . end | .State')
# Print out the service names and statuses
for i in $(seq 0 $(expr $(echo $services | wc -w) - 1)); do
service=$(echo $services | cut -d' ' -f $(expr $i + 1))
state=$(echo $states | cut -d' ' -f $(expr $i + 1))
echo -n "- $service: "
if [ "$state" == "running" ]; then
colorized_echo green $state
else
colorized_echo red $state
fi
done
}
prompt_for_marzban_password() {
colorized_echo cyan "This password will be used to access the database and should be strong."
colorized_echo cyan "If you do not enter a custom password, a secure 20-character password will be generated automatically."
# Запрашиваем ввод пароля
read -p "Enter the password for the marzban user (or press Enter to generate a secure default password): " MYSQL_PASSWORD
# Генерация 20-значного пароля, если пользователь оставил поле пустым
if [ -z "$MYSQL_PASSWORD" ]; then
MYSQL_PASSWORD=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 20)
colorized_echo green "A secure password has been generated automatically."
fi