-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvps-init.sh
More file actions
1940 lines (1710 loc) · 67.4 KB
/
Copy pathvps-init.sh
File metadata and controls
1940 lines (1710 loc) · 67.4 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
#!/bin/bash
# =============================================================================
# VPS 初始化脚本 - 安全优先 · 多发行版兼容
# 支持: Debian/Ubuntu, CentOS/RHEL/Fedora/AlmaLinux/Rocky, Arch, Alpine, openSUSE
#
# 核心安全原则:
# 1. 永远不在验证 SSH 密钥登录成功之前禁用密码登录
# 2. 所有关键配置修改前自动备份
# 3. 高风险操作需要用户手动验证后才继续
# 4. 公钥格式校验, 防止粘贴错误
#
# 用法: 以 root 身份运行
# chmod +x vps-init.sh
# bash vps-init.sh # 已经是 root
# sudo bash vps-init.sh # 普通用户通过 sudo 提权
# =============================================================================
set -euo pipefail
# ========================== Root 权限检查 (最早执行) ==========================
if [[ $EUID -ne 0 ]]; then
echo -e "\033[0;31m[ERROR]\033[0m 此脚本必须以 root 身份运行!"
echo ""
if command -v sudo &>/dev/null; then
echo " 请使用以下方式之一:"
echo " sudo bash $0"
echo " sudo -i && bash $0"
else
echo " 当前系统未安装 sudo, 请先切换到 root:"
echo " su - root"
echo " bash $0"
fi
exit 1
fi
# ========================== 确保 sudo 可用 (root 下预装) ==========================
# 许多极简系统/容器镜像不带 sudo, 但后续创建的普通用户需要它
if ! command -v sudo &>/dev/null; then
echo -e "\033[0;34m[INFO]\033[0m 检测到 sudo 未安装, 正在预装..."
if command -v apt-get &>/dev/null; then
apt-get update -qq && apt-get install -y -qq sudo >/dev/null 2>&1
elif command -v yum &>/dev/null; then
yum install -y -q sudo >/dev/null 2>&1
elif command -v dnf &>/dev/null; then
dnf install -y -q sudo >/dev/null 2>&1
elif command -v pacman &>/dev/null; then
pacman -Sy --noconfirm sudo >/dev/null 2>&1
elif command -v apk &>/dev/null; then
apk add --no-cache sudo >/dev/null 2>&1
elif command -v zypper &>/dev/null; then
zypper install -y sudo >/dev/null 2>&1
fi
if command -v sudo &>/dev/null; then
echo -e "\033[0;32m[OK]\033[0m sudo 安装成功"
else
echo -e "\033[1;33m[WARN]\033[0m sudo 安装失败, 新用户可能无法使用 sudo 提权"
fi
fi
# ========================== 默认配置 ==========================
DEFAULT_USER="deploy"
DEFAULT_SSH_PORT="22000"
DEFAULT_TIMEZONE="Asia/Shanghai"
# ========================== 颜色 ==========================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
# ========================== 日志 ==========================
info() { echo -e "${BLUE}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[OK]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; }
step() { echo -e "\n${BOLD}${CYAN}========== $* ==========${NC}\n"; }
# ========================== 全局状态 ==========================
NEW_USER=""
NEW_SSH_PORT=""
SSH_KEY_CONFIGURED=false
# 由 detect_os 填充
OS_FAMILY="" # debian | rhel | arch | suse | alpine
OS_ID="" # ubuntu, debian, centos, fedora, alma, rocky, arch, alpine, opensuse-*
OS_VERSION="" # 主版本号
SUDO_GROUP="" # sudo | wheel
SSH_SERVICE="" # ssh | sshd
FW_TYPE="" # ufw | firewalld | iptables
F2B_LOGPATH="" # fail2ban 日志路径
F2B_BACKEND="" # fail2ban backend: auto | systemd
# ========================== 工具函数 ==========================
confirm() {
local prompt="${1:-确认继续?}"
local default="${2:-y}"
local answer
if [[ "$default" == "y" ]]; then
read -rp "$(echo -e "${YELLOW}$prompt [Y/n]: ${NC}")" answer
answer="${answer:-y}"
else
read -rp "$(echo -e "${YELLOW}$prompt [y/N]: ${NC}")" answer
answer="${answer:-n}"
fi
[[ "${answer,,}" == "y" ]]
}
get_server_ip() {
curl -s --max-time 5 ifconfig.me 2>/dev/null \
|| curl -s --max-time 5 icanhazip.com 2>/dev/null \
|| wget -qO- --timeout=5 ifconfig.me 2>/dev/null \
|| echo "无法获取"
}
validate_ssh_pubkey() {
local key="$1"
[[ -z "$key" ]] && return 1
echo "$key" | grep -qE '^(ssh-(ed25519|rsa)|ecdsa-sha2-nistp(256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com) [A-Za-z0-9+/=]+'
}
validate_port() {
local port="$1"
[[ "$port" =~ ^[0-9]+$ ]] && (( port >= 1024 && port <= 65535 ))
}
get_current_ssh_port() {
local port
port=$(grep -E '^\s*Port\s+' /etc/ssh/sshd_config 2>/dev/null | awk '{print $2}' | head -1)
echo "${port:-22}"
}
# ========================== 发行版检测与适配 ==========================
detect_os() {
if [[ ! -f /etc/os-release ]]; then
error "无法检测操作系统 (/etc/os-release 不存在)"
error "此脚本支持: Debian/Ubuntu, CentOS/RHEL/Fedora/Alma/Rocky, Arch, Alpine, openSUSE"
exit 1
fi
. /etc/os-release
OS_ID="${ID,,}"
OS_VERSION="${VERSION_ID%%.*}"
case "$OS_ID" in
ubuntu|debian|linuxmint|pop|kali|deepin)
OS_FAMILY="debian"
SUDO_GROUP="sudo"
SSH_SERVICE="ssh"
FW_TYPE="ufw"
# Debian 12 / Ubuntu 24.04+ 默认不再生成 /var/log/auth.log
# (rsyslog 不再默认安装, 日志只写入 systemd journal)
if [[ -f /var/log/auth.log ]]; then
F2B_LOGPATH="/var/log/auth.log"
F2B_BACKEND="auto"
else
F2B_LOGPATH=""
F2B_BACKEND="systemd"
fi
;;
centos|rhel|almalinux|rocky|ol|scientific)
OS_FAMILY="rhel"
SUDO_GROUP="wheel"
SSH_SERVICE="sshd"
FW_TYPE="firewalld"
F2B_BACKEND="systemd"
if [[ -f /var/log/secure ]]; then
F2B_LOGPATH="/var/log/secure"
else
F2B_LOGPATH="%(sshd_log)s"
F2B_BACKEND="systemd"
fi
;;
fedora)
OS_FAMILY="rhel"
SUDO_GROUP="wheel"
SSH_SERVICE="sshd"
FW_TYPE="firewalld"
F2B_LOGPATH="%(sshd_log)s"
F2B_BACKEND="systemd"
;;
arch|manjaro|endeavouros)
OS_FAMILY="arch"
SUDO_GROUP="wheel"
SSH_SERVICE="sshd"
FW_TYPE="iptables"
F2B_LOGPATH="%(sshd_log)s"
F2B_BACKEND="systemd"
;;
opensuse*|sles)
OS_FAMILY="suse"
SUDO_GROUP="wheel"
SSH_SERVICE="sshd"
FW_TYPE="firewalld"
F2B_LOGPATH="/var/log/messages"
F2B_BACKEND="auto"
;;
alpine)
OS_FAMILY="alpine"
SUDO_GROUP="wheel"
SSH_SERVICE="sshd"
FW_TYPE="iptables"
F2B_LOGPATH="/var/log/messages"
F2B_BACKEND="auto"
;;
*)
warn "未知发行版: $OS_ID, 将尝试自动检测包管理器"
if command -v apt &>/dev/null; then
OS_FAMILY="debian"
elif command -v dnf &>/dev/null; then
OS_FAMILY="rhel"
elif command -v yum &>/dev/null; then
OS_FAMILY="rhel"
elif command -v pacman &>/dev/null; then
OS_FAMILY="arch"
elif command -v zypper &>/dev/null; then
OS_FAMILY="suse"
elif command -v apk &>/dev/null; then
OS_FAMILY="alpine"
else
error "无法检测包管理器, 脚本无法继续"
exit 1
fi
SUDO_GROUP="wheel"
SSH_SERVICE="sshd"
FW_TYPE="iptables"
F2B_LOGPATH="/var/log/auth.log"
F2B_BACKEND="auto"
;;
esac
# Debian 系的 SSH 服务名可能是 ssh 或 sshd, 实际检测一下
if [[ "$OS_FAMILY" == "debian" ]]; then
if systemctl list-unit-files sshd.service &>/dev/null 2>&1; then
SSH_SERVICE="sshd"
fi
fi
}
# ========================== 包管理器抽象层 ==========================
pkg_update() {
case "$OS_FAMILY" in
debian) apt update -y && apt full-upgrade -y ;;
rhel)
if command -v dnf &>/dev/null; then
dnf upgrade -y
else
yum update -y
fi
;;
arch) pacman -Syu --noconfirm ;;
suse) zypper refresh && zypper update -y ;;
alpine) apk update && apk upgrade ;;
esac
}
pkg_clean() {
case "$OS_FAMILY" in
debian) apt autoremove -y && apt autoclean -y ;;
rhel)
if command -v dnf &>/dev/null; then
dnf autoremove -y
else
yum autoremove -y 2>/dev/null || true
fi
;;
arch) pacman -Sc --noconfirm 2>/dev/null || true ;;
suse) zypper clean ;;
alpine) apk cache clean 2>/dev/null || true ;;
esac
}
pkg_install() {
local packages=("$@")
case "$OS_FAMILY" in
debian) apt install -y "${packages[@]}" ;;
rhel)
if command -v dnf &>/dev/null; then
dnf install -y "${packages[@]}"
else
yum install -y "${packages[@]}"
fi
;;
arch) pacman -S --noconfirm --needed "${packages[@]}" ;;
suse) zypper install -y "${packages[@]}" ;;
alpine) apk add "${packages[@]}" ;;
esac
}
pkg_is_installed() {
local pkg="$1"
case "$OS_FAMILY" in
debian) dpkg -l "$pkg" 2>/dev/null | grep -q "^ii" ;;
rhel) rpm -q "$pkg" &>/dev/null ;;
arch) pacman -Qi "$pkg" &>/dev/null ;;
suse) rpm -q "$pkg" &>/dev/null ;;
alpine) apk info -e "$pkg" &>/dev/null ;;
esac
}
get_base_packages() {
local common_all="curl wget git vim htop tree unzip"
case "$OS_FAMILY" in
debian)
echo "sudo $common_all net-tools ufw fail2ban"
;;
rhel)
# EPEL is needed for fail2ban on RHEL-based
if [[ "$OS_ID" != "fedora" ]]; then
echo "sudo $common_all net-tools firewalld fail2ban epel-release"
else
echo "sudo $common_all net-tools firewalld fail2ban"
fi
;;
arch)
echo "sudo $common_all net-tools ufw fail2ban"
;;
suse)
echo "sudo $common_all net-tools firewalld fail2ban"
;;
alpine)
echo "sudo $common_all net-tools fail2ban ip6tables"
;;
esac
}
check_reboot_required() {
if [[ "$OS_FAMILY" == "debian" ]]; then
[[ -f /var/run/reboot-required ]]
elif [[ "$OS_FAMILY" == "rhel" ]]; then
if command -v needs-restarting &>/dev/null; then
needs-restarting -r &>/dev/null
[[ $? -eq 1 ]]
else
false
fi
else
false
fi
}
# ========================== 防火墙抽象层 ==========================
fw_allow_port() {
local port="$1"
local proto="${2:-tcp}"
local comment="${3:-}"
case "$FW_TYPE" in
ufw)
ufw allow "$port/$proto" ${comment:+comment "$comment"} 2>/dev/null \
|| ufw allow "$port/$proto"
;;
firewalld)
firewall-cmd --permanent --add-port="$port/$proto"
;;
iptables)
iptables -A INPUT -p "$proto" --dport "$port" -j ACCEPT
if command -v ip6tables &>/dev/null; then
ip6tables -A INPUT -p "$proto" --dport "$port" -j ACCEPT
fi
;;
esac
}
fw_set_defaults() {
case "$FW_TYPE" in
ufw)
ufw default deny incoming
ufw default allow outgoing
;;
firewalld)
firewall-cmd --set-default-zone=drop 2>/dev/null || true
firewall-cmd --permanent --zone=drop --add-service=dhcpv6-client 2>/dev/null || true
;;
iptables)
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
if command -v ip6tables &>/dev/null; then
ip6tables -P INPUT DROP
ip6tables -P FORWARD DROP
ip6tables -P OUTPUT ACCEPT
ip6tables -A INPUT -i lo -j ACCEPT
ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
fi
;;
esac
}
fw_enable() {
case "$FW_TYPE" in
ufw)
echo "y" | ufw enable
;;
firewalld)
systemctl enable --now firewalld
firewall-cmd --reload
;;
iptables)
# 持久化 iptables 规则
if command -v iptables-save &>/dev/null; then
mkdir -p /etc/iptables
iptables-save > /etc/iptables/rules.v4
if command -v ip6tables-save &>/dev/null; then
ip6tables-save > /etc/iptables/rules.v6
fi
success "iptables 规则已保存"
if [[ "$OS_FAMILY" == "arch" ]]; then
systemctl enable iptables 2>/dev/null || true
fi
fi
;;
esac
}
fw_status() {
case "$FW_TYPE" in
ufw) ufw status verbose ;;
firewalld) firewall-cmd --list-all ;;
iptables) iptables -L -n --line-numbers ;;
esac
}
fw_is_active() {
case "$FW_TYPE" in
ufw) ufw status 2>/dev/null | grep -q "Status: active" ;;
firewalld) systemctl is-active firewalld &>/dev/null ;;
iptables) iptables -L -n 2>/dev/null | grep -qv "^$" ;;
esac
}
# ========================== SSH 服务操作 ==========================
ssh_restart() {
if systemctl restart "$SSH_SERVICE" 2>/dev/null; then
return 0
elif systemctl restart sshd 2>/dev/null; then
return 0
elif systemctl restart ssh 2>/dev/null; then
return 0
elif service sshd restart 2>/dev/null; then
return 0
elif rc-service sshd restart 2>/dev/null; then
return 0
else
error "无法重启 SSH 服务"
return 1
fi
}
ssh_syntax_check() {
sshd -t 2>/dev/null
}
# ========================== 用户创建抽象层 ==========================
create_system_user() {
local username="$1"
case "$OS_FAMILY" in
debian)
adduser --gecos "" "$username"
;;
rhel|arch|suse)
useradd -m -s /bin/bash "$username" 2>/dev/null || useradd -m "$username"
info "请为用户 '$username' 设置密码:"
passwd "$username"
;;
alpine)
adduser -s /bin/ash "$username"
;;
esac
usermod -aG "$SUDO_GROUP" "$username"
# RHEL/Arch: 确保 wheel 组在 sudoers 中启用
if [[ "$SUDO_GROUP" == "wheel" ]]; then
local sudoers="/etc/sudoers"
if [ -f "$sudoers" ]; then
# 取消注释 %wheel 行
if grep -q "^#.*%wheel.*ALL=(ALL).*ALL" "$sudoers" 2>/dev/null; then
sed -i 's/^#\s*\(%wheel\s\+ALL=(ALL)\s\+ALL\)/\1/' "$sudoers" 2>/dev/null || true
fi
if grep -q "^#.*%wheel.*ALL=(ALL:ALL).*ALL" "$sudoers" 2>/dev/null; then
sed -i 's/^#\s*\(%wheel\s\+ALL=(ALL:ALL)\s\+ALL\)/\1/' "$sudoers" 2>/dev/null || true
fi
fi
fi
}
# ========================== SELinux 处理 ==========================
handle_selinux_ssh() {
if ! command -v getenforce &>/dev/null; then
return 0
fi
local se_status
se_status=$(getenforce 2>/dev/null || echo "Disabled")
if [[ "$se_status" == "Disabled" ]] || [[ "$se_status" == "Permissive" ]]; then
return 0
fi
info "检测到 SELinux 处于 Enforcing 模式"
# 如果端口改了, 需要告诉 SELinux
if [[ -n "${NEW_SSH_PORT:-}" ]] && [[ "$NEW_SSH_PORT" != "22" ]]; then
if command -v semanage &>/dev/null; then
info "正在为 SELinux 注册 SSH 端口 $NEW_SSH_PORT..."
semanage port -a -t ssh_port_t -p tcp "$NEW_SSH_PORT" 2>/dev/null \
|| semanage port -m -t ssh_port_t -p tcp "$NEW_SSH_PORT" 2>/dev/null \
|| warn "SELinux 端口注册失败, 可能需要手动处理"
else
warn "semanage 未安装, 无法自动配置 SELinux SSH 端口"
warn "请手动安装: $(
case $OS_FAMILY in
rhel) echo 'dnf install policycoreutils-python-utils' ;;
*) echo 'policycoreutils-python-utils' ;;
esac
)"
warn "然后执行: semanage port -a -t ssh_port_t -p tcp $NEW_SSH_PORT"
fi
fi
# 修复 authorized_keys 的 SELinux 上下文
if command -v restorecon &>/dev/null && [[ -n "${NEW_USER:-}" ]]; then
restorecon -Rv "/home/${NEW_USER}/.ssh" 2>/dev/null || true
fi
}
# ========================== 自动更新抽象层 ==========================
setup_auto_updates() {
case "$OS_FAMILY" in
debian)
pkg_install unattended-upgrades
echo 'APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";' > /etc/apt/apt.conf.d/20auto-upgrades
success "自动安全更新已启用 (unattended-upgrades)"
;;
rhel)
if command -v dnf &>/dev/null; then
pkg_install dnf-automatic
# 仅安装安全更新
sed -i 's/^upgrade_type\s*=.*/upgrade_type = security/' /etc/dnf/automatic.conf 2>/dev/null || true
sed -i 's/^apply_updates\s*=.*/apply_updates = yes/' /etc/dnf/automatic.conf 2>/dev/null || true
systemctl enable --now dnf-automatic.timer
success "自动安全更新已启用 (dnf-automatic)"
else
pkg_install yum-cron
sed -i 's/^update_cmd\s*=.*/update_cmd = security/' /etc/yum/yum-cron.conf 2>/dev/null || true
sed -i 's/^apply_updates\s*=.*/apply_updates = yes/' /etc/yum/yum-cron.conf 2>/dev/null || true
systemctl enable --now yum-cron
success "自动安全更新已启用 (yum-cron)"
fi
;;
arch)
warn "Arch Linux 不建议自动更新 (滚动发行版, 更新可能需要手动干预)"
info "建议定期手动执行: pacman -Syu"
;;
suse)
zypper install -y yast2-online-update-configuration 2>/dev/null || true
info "openSUSE 请通过 YaST 配置自动更新"
;;
alpine)
info "Alpine 请通过 cron 配置 apk upgrade --available"
;;
esac
}
# ========================== 阶段 0: 前置检查 ==========================
phase0_precheck() {
step "阶段 0/7: 前置检查"
detect_os
info "系统信息:"
info " 发行版: ${PRETTY_NAME:-$OS_ID}"
info " OS 家族: $OS_FAMILY"
info " 内核: $(uname -r)"
info " CPU: $(nproc) 核 ($(lscpu 2>/dev/null | grep 'Model name' | sed 's/.*:\s*//' || echo '未知'))"
info " 内存: $(free -h 2>/dev/null | awk '/^Mem:/{print $2}' || echo '未知')"
info " 磁盘: $(df -h / 2>/dev/null | awk 'NR==2{print $2 " (已用 " $5 ")"}' || echo '未知')"
info " 公网 IP: $(get_server_ip)"
echo ""
info "适配方案:"
info " 包管理: $OS_FAMILY"
info " 防火墙: $FW_TYPE"
info " SSH 服务: $SSH_SERVICE"
info " sudo 组: $SUDO_GROUP"
# SELinux 状态
if command -v getenforce &>/dev/null; then
local se_status
se_status=$(getenforce 2>/dev/null || echo "未知")
info " SELinux: $se_status"
if [[ "$se_status" == "Enforcing" ]]; then
warn "SELinux 处于强制模式, 修改 SSH 端口时需要额外配置 (脚本会自动处理)"
fi
fi
echo ""
success "前置检查通过"
if ! confirm "以上信息是否正确? 是否继续初始化?"; then
info "已取消"
exit 0
fi
}
# ========================== EOL 源修复 ==========================
# 各发行版 EOL 后官方镜像下线, 需要切换到归档源才能安装软件包
# CentOS 7/8 → vault.centos.org
# Debian ≤10 → archive.debian.org
# Ubuntu EOL → old-releases.ubuntu.com
# Fedora EOL → archives.fedoraproject.org
_check_url_reachable() {
local url="$1"
if command -v curl &>/dev/null; then
curl -sfL --head --max-time 10 "$url" >/dev/null 2>&1
elif command -v wget &>/dev/null; then
wget -q --spider --timeout=10 "$url" 2>/dev/null
else
return 0
fi
}
_fix_centos_eol() {
local vault_base="http://vault.centos.org"
local needs_fix=false
if [[ "$OS_VERSION" == "7" || "$OS_VERSION" == "8" ]]; then
for repo in /etc/yum.repos.d/CentOS-*.repo; do
[[ -f "$repo" ]] || continue
if grep -qE '^\s*mirrorlist=' "$repo" 2>/dev/null; then
needs_fix=true
break
fi
done
else
return 0
fi
$needs_fix || return 0
warn "CentOS $OS_VERSION 已 EOL, 官方镜像已下线"
info "将 yum 源切换到 vault.centos.org..."
for repo in /etc/yum.repos.d/CentOS-*.repo; do
[[ -f "$repo" ]] || continue
cp "$repo" "${repo}.bak.$(date +%s)" 2>/dev/null || true
sed -i 's|^\s*mirrorlist=|#mirrorlist=|g' "$repo"
if [[ "$OS_VERSION" == "7" ]]; then
sed -i 's|^#\s*baseurl=http://mirror.centos.org/centos|baseurl='"$vault_base"'/centos|g' "$repo"
sed -i 's|^baseurl=http://mirror.centos.org/centos|baseurl='"$vault_base"'/centos|g' "$repo"
else
sed -i 's|^#\s*baseurl=http://mirror.centos.org|baseurl='"$vault_base"'/centos|g' "$repo"
sed -i 's|^baseurl=http://mirror.centos.org|baseurl='"$vault_base"'/centos|g' "$repo"
fi
done
yum clean all &>/dev/null || true
success "yum 源已切换到 vault.centos.org"
}
_fix_debian_eol() {
[[ "$OS_VERSION" -ge 11 ]] && return 0
grep -q "archive.debian.org" /etc/apt/sources.list 2>/dev/null && return 0
local codename
codename=$(. /etc/os-release && echo "${VERSION_CODENAME:-}")
[[ -z "$codename" ]] && return 0
if _check_url_reachable "http://deb.debian.org/debian/dists/${codename}/Release"; then
return 0
fi
warn "Debian $OS_VERSION ($codename) 已 EOL, 常规镜像已下线"
info "将 apt 源切换到 archive.debian.org..."
cp /etc/apt/sources.list "/etc/apt/sources.list.bak.$(date +%s)" 2>/dev/null || true
sed -i -E 's|https?://[a-zA-Z0-9.\-]+/debian/?|http://archive.debian.org/debian/|g' /etc/apt/sources.list
sed -i -E 's|https?://security\.debian\.org[^ ]*|http://archive.debian.org/debian-security/|g' /etc/apt/sources.list
echo 'Acquire::Check-Valid-Until "false";' > /etc/apt/apt.conf.d/99no-check-valid-until
apt-get clean 2>/dev/null || true
success "apt 源已切换到 archive.debian.org"
}
_fix_ubuntu_eol() {
grep -q "old-releases.ubuntu.com" /etc/apt/sources.list 2>/dev/null && return 0
local codename
codename=$(. /etc/os-release && echo "${VERSION_CODENAME:-}")
[[ -z "$codename" ]] && return 0
if _check_url_reachable "http://archive.ubuntu.com/ubuntu/dists/${codename}/Release"; then
return 0
fi
if ! _check_url_reachable "http://old-releases.ubuntu.com/ubuntu/dists/${codename}/Release"; then
return 0
fi
warn "Ubuntu ($codename) 已 EOL, 常规镜像已下线"
info "将 apt 源切换到 old-releases.ubuntu.com..."
cp /etc/apt/sources.list "/etc/apt/sources.list.bak.$(date +%s)" 2>/dev/null || true
sed -i -E 's|https?://[a-zA-Z0-9.\-]+/ubuntu/?|http://old-releases.ubuntu.com/ubuntu/|g' /etc/apt/sources.list
sed -i -E 's|https?://security\.ubuntu\.com/ubuntu/?|http://old-releases.ubuntu.com/ubuntu/|g' /etc/apt/sources.list
apt-get clean 2>/dev/null || true
success "apt 源已切换到 old-releases.ubuntu.com"
}
_fix_fedora_eol() {
local release
release=$(rpm -E %fedora 2>/dev/null || echo "$OS_VERSION")
if _check_url_reachable "https://mirrors.fedoraproject.org/metalink?repo=fedora-${release}&arch=$(uname -m)"; then
return 0
fi
local has_metalink=false
for repo in /etc/yum.repos.d/fedora*.repo; do
[[ -f "$repo" ]] || continue
if grep -qE '^\s*metalink=' "$repo" 2>/dev/null; then
has_metalink=true
break
fi
done
$has_metalink || return 0
warn "Fedora $release 已 EOL, 标准镜像已下线"
info "将 dnf 源切换到 archives.fedoraproject.org..."
for repo in /etc/yum.repos.d/fedora*.repo; do
[[ -f "$repo" ]] || continue
cp "$repo" "${repo}.bak.$(date +%s)" 2>/dev/null || true
sed -i 's|^\s*metalink=|#metalink=|g' "$repo"
sed -i 's|^#baseurl=http://download.example/pub/fedora/linux|baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux|g' "$repo"
done
dnf clean all &>/dev/null || true
success "dnf 源已切换到 archives.fedoraproject.org"
}
fix_eol_repos() {
case "$OS_ID" in
centos) _fix_centos_eol ;;
debian) _fix_debian_eol ;;
ubuntu) _fix_ubuntu_eol ;;
fedora) _fix_fedora_eol ;;
esac
}
# ========================== 阶段 1: 系统更新与工具安装 ==========================
phase1_system_update() {
step "阶段 1/7: 系统更新与基础工具安装"
# --- EOL 源修复 (必须在任何包操作之前) ---
fix_eol_repos
# --- EPEL 源 (RHEL 家族需要) ---
if [[ "$OS_FAMILY" == "rhel" ]] && [[ "$OS_ID" != "fedora" ]]; then
if ! pkg_is_installed epel-release 2>/dev/null; then
info "RHEL 系需要 EPEL 源 (提供 fail2ban 等软件)..."
if confirm "是否安装 EPEL 源?"; then
if command -v dnf &>/dev/null; then
dnf install -y epel-release
else
yum install -y epel-release
fi
success "EPEL 源已安装"
fi
else
success "EPEL 源已存在"
fi
fi
# --- 系统更新 ---
if confirm "是否更新系统软件包?"; then
info "正在更新..."
pkg_update
info "正在清理..."
pkg_clean
if check_reboot_required; then
warn "系统更新后需要重启才能完全生效"
warn "建议: 完成所有配置后手动 reboot"
else
success "更新完成"
fi
else
info "跳过系统更新"
fi
# --- 工具安装 ---
echo ""
local packages
packages=$(get_base_packages)
info "将安装以下软件包: $packages"
if confirm "是否安装基础工具?"; then
info "正在安装..."
# shellcheck disable=SC2086
pkg_install $packages 2>&1 || {
warn "部分软件包安装失败, 尝试逐个安装..."
for pkg in $packages; do
pkg_install "$pkg" 2>/dev/null || warn " $pkg 安装失败, 跳过"
done
}
success "基础工具安装完成"
else
warn "跳过工具安装, 检查关键依赖..."
for cmd in sudo curl; do
if ! command -v "$cmd" &>/dev/null; then
warn "$cmd 未安装, 后续功能可能受限"
fi
done
fi
}
# ========================== 阶段 2: 创建非 root 用户 ==========================
phase2_create_user() {
step "阶段 2/7: 用户配置"
echo "创建独立用户可以避免日常操作使用 root, 提高安全性。"
echo "如果你习惯直接用 root, 也可以跳过。"
echo ""
if ! confirm "是否创建新的非 root 用户?" "n"; then
info "跳过用户创建, 将继续使用 root"
NEW_USER=""
return 0
fi
local username
read -rp "$(echo -e "${CYAN}请输入新用户名 [默认: $DEFAULT_USER]: ${NC}")" username
username="${username:-$DEFAULT_USER}"
if ! echo "$username" | grep -qE '^[a-z_][a-z0-9_-]{0,31}$'; then
error "用户名不合法 (只允许小写字母、数字、下划线、连字符, 且以字母或下划线开头)"
return 1
fi
if id "$username" &>/dev/null; then
warn "用户 '$username' 已存在"
if confirm "是否直接使用该用户继续?"; then
NEW_USER="$username"
usermod -aG "$SUDO_GROUP" "$username" 2>/dev/null || true
success "将使用已有用户: $username (已确保在 $SUDO_GROUP 组)"
return 0
else
error "请重新运行脚本并选择其他用户名"
exit 1
fi
fi
info "正在创建用户 '$username'..."
create_system_user "$username"
success "用户 '$username' 已创建并加入 $SUDO_GROUP 组"
NEW_USER="$username"
}
# ========================== 阶段 3: SSH 密钥配置 ==========================
phase3_ssh_key() {
step "阶段 3/7: SSH 密钥配置 (关键安全步骤)"
echo -e "${BOLD}此步骤将配置 SSH 密钥登录。${NC}"
echo ""
echo "你需要在 ${BOLD}本地电脑${NC} 上准备好 SSH 公钥。"
echo "如果还没有, 请在本地电脑上执行:"
echo -e " ${CYAN}ssh-keygen -t ed25519 -C \"[email protected]\"${NC}"
echo ""
echo "然后查看公钥:"
echo -e " ${CYAN}cat ~/.ssh/id_ed25519.pub${NC} (Linux/Mac)"
echo -e " ${CYAN}type %USERPROFILE%\\.ssh\\id_ed25519.pub${NC} (Windows CMD)"
echo -e " ${CYAN}cat \$env:USERPROFILE\\.ssh\\id_ed25519.pub${NC} (PowerShell)"
echo ""
if ! confirm "你是否已经准备好 SSH 公钥?"; then
warn "跳过 SSH 密钥配置"
warn "后续的 SSH 安全加固将不会禁用密码登录"
SSH_KEY_CONFIGURED=false
return 0
fi
local pubkey=""
local attempts=0
local max_attempts=3
while (( attempts < max_attempts )); do
echo ""
echo -e "${CYAN}请粘贴你的 SSH 公钥 (以 ssh-ed25519 或 ssh-rsa 开头的完整一行):${NC}"
read -r pubkey
pubkey=$(echo "$pubkey" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
if validate_ssh_pubkey "$pubkey"; then
local key_type
key_type=$(echo "$pubkey" | awk '{print $1}')
local key_comment
key_comment=$(echo "$pubkey" | awk '{print $3}')
echo ""
success "公钥格式验证通过"
info " 类型: $key_type"
info " 备注: ${key_comment:-无}"
echo ""
if confirm "确认使用这个公钥?"; then
break
else
pubkey=""
info "请重新输入"
fi
else
attempts=$((attempts + 1))
error "公钥格式不正确! (尝试 $attempts/$max_attempts)"
echo "公钥应该类似:"
echo " ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... user@host"
echo " ssh-rsa AAAAB3NzaC1yc2EAAAA... user@host"
echo ""
if (( attempts >= max_attempts )); then
error "多次输入失败, 跳过密钥配置"
SSH_KEY_CONFIGURED=false
return 0
fi
fi
done
if [[ -z "$pubkey" ]]; then
SSH_KEY_CONFIGURED=false
return 0
fi
# 安装公钥
local target_user="${NEW_USER:-root}"
local user_home
user_home=$(eval echo "~${target_user}")
local ssh_dir="$user_home/.ssh"
local auth_keys="$ssh_dir/authorized_keys"
mkdir -p "$ssh_dir"
chmod 700 "$ssh_dir"
if [ -f "$auth_keys" ] && grep -qF "$pubkey" "$auth_keys" 2>/dev/null; then
warn "该公钥已存在于 authorized_keys 中, 无需重复添加"
else
echo "$pubkey" >> "$auth_keys"
success "公钥已写入 $auth_keys"
fi
chmod 600 "$auth_keys"
chown -R "${target_user}:${target_user}" "$ssh_dir"
# SELinux: 修复上下文
if command -v restorecon &>/dev/null; then
restorecon -Rv "$ssh_dir" 2>/dev/null || true
fi
# === 关键验证 ===
echo ""
echo -e "${RED}${BOLD}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}${BOLD}║ 请 务 必 完 成 以 下 验 证 步 骤 ║${NC}"
echo -e "${RED}${BOLD}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "请 ${BOLD}新开一个终端窗口${NC}, 测试密钥登录:"
echo ""
local server_ip
server_ip=$(get_server_ip)
local current_port
current_port=$(get_current_ssh_port)
echo -e " ${CYAN}ssh -p $current_port ${NEW_USER:-root}@${server_ip}${NC}"
echo ""
echo -e "${YELLOW}请确认: 不需要输入 服务器密码 就能登录成功${NC}"
echo -e "${YELLOW}(如果给私钥设了 passphrase, 会提示输入私钥密码, 这是正常的)${NC}"
echo ""
if confirm "密钥登录测试是否成功? (一定要先测试再回答!)"; then
SSH_KEY_CONFIGURED=true
success "SSH 密钥验证通过, 后续将安全地禁用密码登录"
else
SSH_KEY_CONFIGURED=false
warn "密钥登录未成功"
echo ""
echo "可能的原因:"
echo " 1. 公钥/私钥不匹配"
echo " 2. 文件权限不正确 (检查: ls -la $ssh_dir)"
if command -v getenforce &>/dev/null; then
echo " 3. SELinux 阻止访问 (检查: audit2why < /var/log/audit/audit.log)"
fi
echo ""
warn "密码登录将保持开启状态以防止被锁定"