Created
November 25, 2025 06:11
-
-
Save Ryaang/1f1dd6caa714e3e4844b545e83bd7b98 to your computer and use it in GitHub Desktop.
新服务器安全加固脚本
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Ubuntu 24 安全初始化脚本 | |
| # 请以 root 用户运行: sudo bash secure-init.sh | |
| # 1. 输入新用户名 | |
| read -p "请输入新用户名: " NEWUSER | |
| adduser $NEWUSER | |
| usermod -aG sudo $NEWUSER | |
| # 2. 输入公钥并写入 authorized_keys | |
| read -p "请粘贴该用户的公钥: " USERKEY | |
| mkdir -p /home/$NEWUSER/.ssh | |
| echo $USERKEY >> /home/$NEWUSER/.ssh/authorized_keys | |
| chown -R $NEWUSER:$NEWUSER /home/$NEWUSER/.ssh | |
| chmod 700 /home/$NEWUSER/.ssh | |
| chmod 600 /home/$NEWUSER/.ssh/authorized_keys | |
| # 3. 禁用 root 登录 & 密码登录 | |
| sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config | |
| sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config | |
| # 4. 可选:修改 SSH 端口 | |
| read -p "是否修改 SSH 端口? (y/n): " CHANGEPORT | |
| if [ "$CHANGEPORT" == "y" ]; then | |
| read -p "请输入新的端口号: " NEWPORT | |
| sed -i "s/^#\?Port.*/Port $NEWPORT/" /etc/ssh/sshd_config | |
| ufw allow $NEWPORT/tcp | |
| else | |
| ufw allow ssh | |
| fi | |
| # 5. 重启 SSH 服务 | |
| systemctl restart ssh | |
| # 6. 安装并配置 UFW 防火墙 | |
| apt update && apt install -y ufw | |
| ufw default deny incoming | |
| ufw default allow outgoing | |
| ufw enable | |
| # 7. 安装 Fail2Ban | |
| apt install -y fail2ban | |
| systemctl enable fail2ban | |
| systemctl start fail2ban | |
| # 8. 启用自动安全更新 | |
| apt install -y unattended-upgrades | |
| dpkg-reconfigure -plow unattended-upgrades | |
| echo "✅ 安全初始化完成!请使用新用户登录,并确保你已在本地配置好私钥。" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment