Dernière activité 1777018731

适用于需要初始化配置多台服务器的场景

doracoin's Avatar doracoin a révisé ce gist 1777018731. Aller à la révision

1 file changed, 72 insertions

server-login-init.sh(fichier créé)

@@ -0,0 +1,72 @@
1 + #!/usr/bin/env bash
2 + set -euo pipefail
3 +
4 + # ====== 可配置项 ======
5 + PUB_KEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQxxxxxxx [email protected]"
6 + SSH_DIR="$HOME/.ssh"
7 + AUTHORIZED_KEYS="$SSH_DIR/authorized_keys"
8 + SSHD_CONFIG="/etc/ssh/sshd_config"
9 +
10 + echo "[INFO] Starting server initialization..."
11 +
12 + # ====== 1. 确保 .ssh 目录存在且权限正确 ======
13 + echo "[INFO] Ensuring .ssh directory..."
14 + mkdir -p "$SSH_DIR"
15 + chmod 700 "$SSH_DIR"
16 +
17 + # ====== 2. 添加公钥(幂等处理:避免重复)======
18 + echo "[INFO] Adding public key..."
19 + touch "$AUTHORIZED_KEYS"
20 +
21 + if ! grep -qF "$PUB_KEY" "$AUTHORIZED_KEYS"; then
22 + echo "$PUB_KEY" >> "$AUTHORIZED_KEYS"
23 + echo "[INFO] Public key added."
24 + else
25 + echo "[INFO] Public key already exists. Skipping."
26 + fi
27 +
28 + chmod 600 "$AUTHORIZED_KEYS"
29 +
30 + # ====== 3. 修改 sshd_config ======
31 + echo "[INFO] Configuring sshd..."
32 +
33 + # 备份
34 + cp "$SSHD_CONFIG" "${SSHD_CONFIG}.bak_$(date +%F_%H-%M-%S)"
35 +
36 + # 确保 PubkeyAuthentication 启用
37 + if grep -q "^#PubkeyAuthentication yes" "$SSHD_CONFIG"; then
38 + sed -i 's/^#PubkeyAuthentication yes/PubkeyAuthentication yes/' "$SSHD_CONFIG"
39 + elif ! grep -q "^PubkeyAuthentication yes" "$SSHD_CONFIG"; then
40 + echo "PubkeyAuthentication yes" >> "$SSHD_CONFIG"
41 + fi
42 +
43 + # ====== 4. 推荐安全增强项 ======
44 +
45 + # 禁止密码登录(互联网服务器强烈建议,内网/专网服务器可选)
46 + # if grep -q "^#PasswordAuthentication" "$SSHD_CONFIG"; then
47 + # sed -i 's/^#PasswordAuthentication.*/PasswordAuthentication no/' "$SSHD_CONFIG"
48 + # elif grep -q "^PasswordAuthentication" "$SSHD_CONFIG"; then
49 + # sed -i 's/^PasswordAuthentication.*/PasswordAuthentication no/' "$SSHD_CONFIG"
50 + # else
51 + # echo "PasswordAuthentication no" >> "$SSHD_CONFIG"
52 + # fi
53 +
54 + # 禁止 root 直接登录(可选)
55 + # if grep -q "^#PermitRootLogin" "$SSHD_CONFIG"; then
56 + # sed -i 's/^#PermitRootLogin.*/PermitRootLogin prohibit-password/' "$SSHD_CONFIG"
57 + # elif grep -q "^PermitRootLogin" "$SSHD_CONFIG"; then
58 + # sed -i 's/^PermitRootLogin.*/PermitRootLogin prohibit-password/' "$SSHD_CONFIG"
59 + # else
60 + # echo "PermitRootLogin prohibit-password" >> "$SSHD_CONFIG"
61 + # fi
62 +
63 + # ====== 5. 重启 sshd ======
64 + echo "[INFO] Restarting sshd..."
65 +
66 + if command -v systemctl >/dev/null 2>&1; then
67 + systemctl restart sshd || systemctl restart ssh
68 + else
69 + service sshd restart || service ssh restart
70 + fi
71 +
72 + echo "[INFO] Done."
Plus récent Plus ancien