54 - 服务器初始化与基线配置
一台全新的 Linux 服务器交付后,第一件事不是安装软件,而是建立标准化的基线配置。主机名、时区、语言环境、时间同步、安全访问、防火墙、自动更新——这些看似琐碎的初始设定决定了后续运维的稳定性。本章覆盖从物理服务器到云实例的完整初始化流程,提供可复用的基线脚本模板。
54.1 服务器 Linux vs 桌面 Linux
核心差异
| 维度 | 桌面 Linux | 服务器 Linux |
|---|---|---|
| 图形界面 | 必装(GNOME/KDE 等) | 通常不装,最小化安装 |
| 运行级别 | graphical.target | multi-user.target |
| 软件包 | 办公、浏览器、多媒体 | Web 服务、数据库、防火墙 |
| 内核参数 | 低延迟桌面响应 | 高网络吞吐 + I/O 优化 |
| 自动更新 | 通常手动 | 建议自动化安全更新 |
| 安全策略 | 相对宽松 | 最小权限,防火墙默认启用 |
| SSH | 可能关闭 | 核心管理通道 |
| Swap | 休眠支持 | 缓解内存压力,低 swappiness |
典型服务器发行版选择
# 稳定性优先 → RHEL / Rocky Linux / AlmaLinux(10 年生命周期)
# 社区驱动 → Debian Stable(~5 年支持)
# 激进更新 + 最新软件 → Arch(滚动更新,适合非关键业务)
# 云原生 → Ubuntu Server(AWS/Azure/GCP 官方支持好)
# 企业网络服务 → openSUSE Leap查看当前发行版信息
cat /etc/os-release
hostnamectl
uname -a
cat /proc/version54.2 首次登录:基础身份设定
设置主机名
# 查看当前主机名
hostnamectl
# 设置静态主机名(永久生效)
sudo hostnamectl set-hostname web-prod-01.example.com
# 同时设置短名和 FQDN
sudo hostnamectl set-hostname web-prod-01 --pretty
sudo hostnamectl set-hostname web-prod-01.example.com
# 验证 /etc/hosts 有对应记录
echo "127.0.1.1 web-prod-01.example.com web-prod-01" | sudo tee -a /etc/hosts
# Debian/Ubuntu 也可编辑 /etc/hostname
sudo vim /etc/hostname设置时区
# 列出所有时区
timedatectl list-timezones | grep Asia
# 设置时区
sudo timedatectl set-timezone Asia/Shanghai
# 验证
timedatectl status
# Local time: Sat 2026-07-24 14:30:00 CST
# Universal time: Sat 2026-07-24 06:30:00 UTC
# RTC time: Sat 2026-07-24 06:30:00
# Time zone: Asia/Shanghai (CST, +0800)
# 同步硬件时钟(RTC)到系统
sudo hwclock --systohc设置语言环境(Locale)
# 查看当前 locale
locale
# 查看已生成的 locale
locale -a
# 生成需要的 locale
sudo vim /etc/locale.gen
# 取消注释:
# en_US.UTF-8 UTF-8
# zh_CN.UTF-8 UTF-8
# Debian/Ubuntu
sudo locale-gen
# RHEL/Fedora
sudo localedef -i en_US -f UTF-8 en_US.UTF-8
# 设置默认 locale
sudo localectl set-locale LANG=en_US.UTF-8
# 或直接编辑
echo "LANG=en_US.UTF-8" | sudo tee /etc/locale.conf # RHEL/Fedora/Arch
echo "LANG=en_US.UTF-8" | sudo tee /etc/default/locale # Debian/Ubuntu54.3 时间同步:NTP 服务
精确的时间对日志关联、SSL 证书验证和分布式协调至关重要。
使用 timedatectl 启用 NTP(推荐,systemd 内置)
# systemd-timesyncd 是 systemd 自带的 SNTP 客户端
# 大多数发行版默认启用
sudo timedatectl set-ntp true
timedatectl timesync-status
# Debian/Ubuntu:需要确保包已安装
sudo apt install systemd-timesyncd
# 编辑配置(可选,指定 NTP 服务器)
sudo vim /etc/systemd/timesyncd.conf[Time]
NTP=ntp.aliyun.com ntp.tuna.tsinghua.edu.cn time.google.com
FallbackNTP=0.pool.ntp.org 1.pool.ntp.orgsudo systemctl restart systemd-timesyncd使用 chrony(高精度场景)
# 安装
sudo apt install chrony # Debian/Ubuntu
sudo dnf install chrony # RHEL/Fedora
sudo pacman -S chrony # Arch
# 编辑配置
sudo vim /etc/chrony/chrony.conf # RHEL/Fedora
sudo vim /etc/chrony/chrony.conf # Debian/Ubuntu(较新版本)# 使用国内 NTP 池
pool ntp.aliyun.com iburst
pool ntp.tuna.tsinghua.edu.cn iburst
# 允许本地网络同步(如果需要作为 NTP 服务器)
# allow 192.168.1.0/24
# 即使没有网络也继续同步(虚拟机环境)
# 允许步进式调整(默认仅慢调)
makestep 1.0 3
# 日志
logdir /var/log/chronysudo systemctl enable --now chronyd
# 查看同步状态
chronyc sources -v
chronyc tracking
chronyc sourcestats
# 显示 NTP 时间偏移
chronyc tracking | grep "System time"54.4 创建管理员用户与 SSH 密钥
创建 sudo 管理员
# 创建用户(-m 创建家目录)
sudo useradd -m -s /bin/bash opsadmin
# 设置密码
sudo passwd opsadmin
# 加入 wheel(RHEL/Fedora/Arch/sudo 组)或 sudo(Debian/Ubuntu)
sudo usermod -aG wheel opsadmin # RHEL/Fedora/Arch
sudo usermod -aG sudo opsadmin # Debian/Ubuntu
# 确保 wheel/sudo 组有 sudo 权限
sudo visudo -f /etc/sudoers.d/10-admin%wheel ALL=(ALL:ALL) NOPASSWD: ALL # RHEL/Fedora/Arch
%sudo ALL=(ALL:ALL) NOPASSWD: ALL # Debian/Ubuntu
SSH 密钥登录配置
# 在本地客户端生成密钥
ssh-keygen -t ed25519 -C "opsadmin@web-prod-01" -f ~/.ssh/id_ed25519_server
# 上传公钥到服务器(方法 1:ssh-copy-id)
ssh-copy-id -i ~/.ssh/id_ed25519_server.pub opsadmin@server-ip
# 上传公钥(方法 2:手动复制)
# 在服务器上:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cat >> ~/.ssh/authorized_keys << 'EOF'
# 粘贴公钥内容
ssh-ed25519 AAAAC3... opsadmin@web-prod-01
EOF
chmod 600 ~/.ssh/authorized_keys禁用 root SSH 登录
sudo vim /etc/ssh/sshd_config.d/99-hardening.confPermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
Protocol 2
sudo sshd -t # 测试配置
sudo systemctl reload sshd详细 SSH 配置见 23-SSH远程管理。
54.5 系统更新与最小化安装
首次全面更新
# Debian / Ubuntu
sudo apt update && sudo apt upgrade -y
sudo apt autoremove --purge -y
# RHEL / Fedora
sudo dnf update -y
sudo dnf autoremove -y
# openSUSE
sudo zypper update -y
# Arch
sudo pacman -Syu --noconfirm移除不必要的包
# Debian/Ubuntu:如果是虚拟化/云实例,移除桌面环境依赖
sudo apt purge --auto-remove gnome* xorg* x11* gdm* lightdm* sddm* -y 2>/dev/null
# RHEL/Fedora
sudo dnf groupremove "Graphical Administration Tools" "GNOME" -y 2>/dev/null
# 移除编译器(如不需要在生产环境编译)
sudo apt purge gcc g++ make build-essential -y # Debian
sudo dnf remove gcc gcc-c++ make -y # RHEL确认最小化服务运行
# 列出所有启用且运行的服务
systemctl list-units --type=service --state=running
# 列出所有监听端口
sudo ss -tlnp
sudo ss -ulnp54.6 自动安全更新
Debian / Ubuntu:unattended-upgrades
sudo apt install unattended-upgrades apt-listchanges -y
# 启用自动更新
sudo dpkg-reconfigure -plow unattended-upgrades
# 选择 "Yes"
# 或手动启用
sudo vim /etc/apt/apt.conf.d/50unattended-upgradesUnattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
"${distro_id}ESMApps:${distro_codename}-apps-security";
"${distro_id}ESM:${distro_codename}-infra-security";
};
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-New-Unused-Dependencies "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "03:00";
Unattended-Upgrade::Mail "ops@example.com";
# 启用定时器
sudo vim /etc/apt/apt.conf.d/20auto-upgradesAPT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
# 测试运行(仅输出计划)
sudo unattended-upgrades --dry-run --verbose
# 查看日志
tail -f /var/log/unattended-upgrades/unattended-upgrades.logRHEL / Fedora:dnf-automatic
sudo dnf install dnf-automatic -y
# 编辑配置
sudo vim /etc/dnf/automatic.conf[commands]
upgrade_type = security
download_updates = yes
apply_updates = yes
[emitters]
emit_via = motd
system_name = web-prod-01
[email]
# 可选:邮件通知
# email_from = root@example.com
# email_to = ops@example.com
# email_host = smtp.example.com# 启用定时任务
sudo systemctl enable --now dnf-automatic.timer
# 查看状态
sudo systemctl status dnf-automatic.timer
sudo systemctl list-timers dnf-automatic-*
# 手动触发一次
sudo dnf-automaticArch Linux
# 使用 pacman-contrib 的 checkupdates
sudo pacman -S pacman-contrib
# 创建 systemd timer
sudo tee /etc/systemd/system/pacman-security-check.service << 'EOF'
[Unit]
Description=Security Update Notification
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/bin/pacman -Sy --noconfirm 2>&1
EOF
sudo tee /etc/systemd/system/pacman-security-check.timer << 'EOF'
[Unit]
Description=Daily security update check
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl enable --now pacman-security-check.timer54.7 防火墙基础设置
UFW(Debian / Ubuntu 推荐)
sudo apt install ufw -y
# 默认策略:拒绝入站,允许出站
sudo ufw default deny incoming
sudo ufw default allow outgoing
# 开放必要端口
sudo ufw allow 22/tcp comment 'SSH'
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'
# 或按服务名
sudo ufw allow ssh
# 限制 SSH 连接速率(防暴力破解)
sudo ufw limit ssh
# 启用防火墙
sudo ufw enable
# 查看状态和规则
sudo ufw status verbose
sudo ufw status numbered
# 删除规则(按编号)
# sudo ufw delete 3
# 禁用 UFW(维护时)
# sudo ufw disablefirewalld(RHEL / Fedora / openSUSE 推荐)
# firewalld 通常预装
sudo dnf install firewalld -y # 如未安装
sudo systemctl enable --now firewalld
# 查看默认区域
sudo firewall-cmd --get-default-zone # 通常是 public
# 查看所有区域
sudo firewall-cmd --list-all-zones
# 开放端口
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-port=8080/tcp
# 重载使生效
sudo firewall-cmd --reload
# 查看当前规则
sudo firewall-cmd --list-all
# 查看已开放的服务
sudo firewall-cmd --list-services
# 创建自定义服务定义
sudo firewall-cmd --permanent --new-service=custom-app
sudo firewall-cmd --permanent --service=custom-app --add-port=9090/tcp
sudo firewall-cmd --permanent --service=custom-app --set-short="Custom App"iptables 直接配置
详见 24-防火墙与安全。
54.8 防暴力破解:fail2ban / sshguard
fail2ban(通用,推荐)
sudo apt install fail2ban -y # Debian/Ubuntu
sudo dnf install fail2ban -y # RHEL/Fedora
sudo pacman -S fail2ban # Arch
# 创建本地配置(覆盖默认值)
sudo vim /etc/fail2ban/jail.local[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
backend = systemd
ignoreip = 127.0.0.1/8 ::1
destemail = ops@example.com
sender = fail2ban@web-prod-01
[sshd]
enabled = true
mode = aggressive
maxretry = 3
bantime = 7200
[nginx-http-auth]
enabled = true
[nginx-botsearch]
enabled = truesudo systemctl enable --now fail2ban
# 查看状态和被封禁 IP
sudo fail2ban-client status
sudo fail2ban-client status sshd
# 手动解封
# sudo fail2ban-client set sshd unbanip 192.168.1.100sshguard(轻量替代)
# Arch Linux 自带;Debian/Ubuntu 可安装
sudo apt install sshguard -y
sudo pacman -S sshguard# 配合 iptables
sudo sshguard -i /var/log/auth.log
# 或配合 systemd journal
sudo systemctl enable --now sshguard
sudo vim /etc/sshguard.conf54.9 Swap 配置
检查当前 Swap
swapon --show
free -h
cat /proc/swaps创建 Swap 文件(现代方式,比分区灵活)
# 创建 2GB Swap 文件
sudo fallocate -l 2G /swapfile
# 或使用 dd(兼容性更好)
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
# 设置权限
sudo chmod 600 /swapfile
# 格式化为 Swap
sudo mkswap /swapfile
# 启用
sudo swapon /swapfile
# 写入 fstab 永久生效
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab调整 swappiness
# 查看当前值(默认 60)
cat /proc/sys/vm/swappiness
# 服务器推荐设为较低值(10-20),减少不必要的 Swap 使用
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.d/99-swap.conf
# 立刻生效
sudo sysctl -p /etc/sysctl.d/99-swap.confSwap 分区方式(传统)
# 如果是安装时已有 Swap 分区,检查并确认
lsblk | grep -i swap
sudo blkid | grep swap54.10 安装运维必备工具
基础工具集
# 一次性安装常用工具
# Debian / Ubuntu
sudo apt install -y \
htop vim git curl wget tmux \
net-tools dnsutils iproute2 \
unzip p7zip-full jq tree lsof \
ncdu iotop sysstat tcpdump \
rsync screen
# RHEL / Fedora
sudo dnf install -y \
htop vim git curl wget tmux \
net-tools bind-utils iproute \
unzip p7zip jq tree lsof \
ncdu iotop sysstat tcpdump \
rsync screen epel-release
# Arch
sudo pacman -S --noconfirm \
htop vim git curl wget tmux \
net-tools bind iproute2 \
unzip p7zip jq tree lsof \
ncdu iotop sysstat tcpdump \
rsync screen
# 安装后启用 sysstat(sar 数据收集)
sudo systemctl enable --now sysstat工具用途速查
| 工具 | 用途 |
|---|---|
htop | 交互式进程监控 |
vim | 文本编辑器 |
git | 版本控制 |
curl / wget | 网络请求与下载 |
tmux / screen | 终端复用(断线保护) |
net-tools / iproute2 | 网络管理(ifconfig/ip) |
dig / nslookup | DNS 诊断 |
jq | JSON 处理 |
lsof | 查看文件被哪些进程打开 |
ncdu | 磁盘使用分析(交互式) |
iotop | I/O 监控 |
sar | 系统活动报告 |
tcpdump | 网络抓包 |
rsync | 文件同步 |
54.11 监控代理部署
Netdata(实时监控,安装简单)
# 一键安装脚本
curl -s https://get.netdata.cloud/kickstart.sh | bash
# 或从包管理器安装
wget -O /tmp/netdata-kickstart.sh https://get.netdata.cloud/kickstart.sh
sh /tmp/netdata-kickstart.sh --stable-channel --disable-telemetry
# 访问 http://<server-ip>:19999
# 配置路径:/etc/netdata/Node Exporter(配合 Prometheus,见 60-监控系统(Prometheus+Grafana))
# 下载最新版
VERSION=$(curl -s https://api.github.com/repos/prometheus/node_exporter/releases/latest | jq -r .tag_name)
wget https://github.com/prometheus/node_exporter/releases/download/${VERSION}/node_exporter-${VERSION}.linux-amd64.tar.gz
tar xzf node_exporter-${VERSION}.linux-amd64.tar.gz
sudo mv node_exporter-${VERSION}.linux-amd64/node_exporter /usr/local/bin/
# 创建 systemd 服务
sudo tee /etc/systemd/system/node_exporter.service << 'EOF'
[Unit]
Description=Node Exporter
After=network.target
[Service]
User=nobody
ExecStart=/usr/local/bin/node_exporter
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now node_exporter54.12 Cloud-init:云实例自动化
什么是 Cloud-init
Cloud-init 是云平台(AWS、GCP、Azure、OpenStack)在实例首次启动时读取的初始化系统。它从 metadata service 获取配置并执行。
# 查看 cloud-init 是否运行过
cloud-init status
# 查看日志
sudo tail -f /var/log/cloud-init-output.log
sudo tail -f /var/log/cloud-init.log
# 重新运行(测试时)
sudo cloud-init clean --logs
sudo cloud-init init --local在本地使用 cloud-init 测试
# 创建 VM 测试配置
sudo apt install cloud-init -y # Debian/Ubuntu
sudo dnf install cloud-init -y # RHEL/Fedora
# 编写 NoCloud 配置
mkdir -p ~/cloudinit-test
cat > ~/cloudinit-test/meta-data << 'EOF'
instance-id: test-vm-01
local-hostname: test-vm
EOF
cat > ~/cloudinit-test/user-data << 'EOF'
#cloud-config
hostname: test-vm
timezone: Asia/Shanghai
users:
- name: opsadmin
ssh_authorized_keys:
- ssh-ed25519 AAAAC3... your-key-here
sudo: ALL=(ALL) NOPASSWD:ALL
groups: wheel
shell: /bin/bash
packages:
- htop
- vim
- git
- curl
- tmux
- ufw
runcmd:
- ufw allow ssh
- ufw --force enable
- timedatectl set-timezone Asia/Shanghai
- systemctl enable --now chronyd
final_message: "Server initialization complete!"
EOF54.13 基线脚本模板
将以上所有步骤整合为一个可复用的初始化脚本:
#!/bin/bash
# baseline-init.sh — 服务器基线初始化脚本
# 支持:Debian/Ubuntu, RHEL/Fedora/Rocky, openSUSE, Arch
set -euo pipefail
# === 可配置参数 ===
HOSTNAME="web-prod-01.example.com"
TIMEZONE="Asia/Shanghai"
ADMIN_USER="opsadmin"
ADMIN_SSH_KEY="ssh-ed25519 AAAAC3..." # 替换为你的公钥
SWAP_SIZE="2G"
SSH_PORT="22"
# === 确认 root 权限 ===
if [[ $EUID -ne 0 ]]; then
echo "请使用 root 或 sudo 运行此脚本"
exit 1
fi
# === 检测发行版 ===
if [ -f /etc/debian_version ]; then
DISTRO="debian"
elif [ -f /etc/redhat-release ]; then
DISTRO="rhel"
elif [ -f /etc/arch-release ]; then
DISTRO="arch"
elif [ -f /etc/SuSE-release ] || [ -f /etc/os-release ] && grep -qi suse /etc/os-release; then
DISTRO="suse"
else
echo "不支持的发行版"
exit 1
fi
echo "检测到发行版:$DISTRO"
# === 设置主机名 ===
hostnamectl set-hostname "$HOSTNAME"
echo "127.0.1.1 $HOSTNAME" >> /etc/hosts
# === 设置时区 ===
timedatectl set-timezone "$TIMEZONE"
timedatectl set-ntp true
# === 系统更新 ===
case $DISTRO in
debian)
apt update && apt upgrade -y
apt install -y chrony ufw fail2ban htop vim git curl wget tmux \
net-tools dnsutils jq tree lsof ncdu sysstat tcpdump rsync
systemctl enable --now chronyd
;;
rhel)
dnf update -y
dnf install -y chrony firewalld fail2ban htop vim git curl wget tmux \
net-tools bind-utils jq tree lsof ncdu sysstat tcpdump rsync
systemctl enable --now chronyd firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --reload
;;
arch)
pacman -Syu --noconfirm
pacman -S --noconfirm chrony ufw fail2ban htop vim git curl wget tmux \
net-tools bind jq tree lsof ncdu sysstat tcpdump rsync
systemctl enable --now chronyd
;;
suse)
zypper update -y
zypper install -y chrony firewalld fail2ban htop vim git curl wget tmux \
net-tools bind-utils jq tree lsof ncdu sysstat tcpdump rsync
systemctl enable --now chronyd firewalld
;;
esac
# === 创建管理员用户 ===
id -u "$ADMIN_USER" &>/dev/null || useradd -m -s /bin/bash "$ADMIN_USER"
case $DISTRO in
debian) usermod -aG sudo "$ADMIN_USER" ;;
*) usermod -aG wheel "$ADMIN_USER" ;;
esac
# === SSH 密钥 ===
mkdir -p /home/$ADMIN_USER/.ssh
echo "$ADMIN_SSH_KEY" >> /home/$ADMIN_USER/.ssh/authorized_keys
chmod 700 /home/$ADMIN_USER/.ssh
chmod 600 /home/$ADMIN_USER/.ssh/authorized_keys
chown -R $ADMIN_USER:$ADMIN_USER /home/$ADMIN_USER/.ssh
# === SSH 加固 ===
cat >> /etc/ssh/sshd_config.d/99-baseline.conf << 'SSHEOF'
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
SSHEOF
systemctl reload sshd
# === 防火墙 ===
case $DISTRO in
debian|arch)
ufw default deny incoming
ufw default allow outgoing
ufw allow $SSH_PORT/tcp
ufw --force enable
;;
rhel|suse)
firewall-cmd --permanent --add-port=$SSH_PORT/tcp
firewall-cmd --reload
;;
esac
# === fail2ban ===
systemctl enable --now fail2ban
# === Swap ===
if ! swapon --show | grep -q swapfile; then
fallocate -l "$SWAP_SIZE" /swapfile 2>/dev/null || dd if=/dev/zero of=/swapfile bs=1M count=2048
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
fi
# === 内核参数 ===
cat > /etc/sysctl.d/99-baseline.conf << 'SYSCTLEOF'
vm.swappiness=10
net.ipv4.tcp_syncookies=1
SYSCTLEOF
sysctl --system
# === 自动安全更新 ===
case $DISTRO in
debian)
apt install -y unattended-upgrades
dpkg-reconfigure -f noninteractive unattended-upgrades
;;
rhel)
dnf install -y dnf-automatic
sed -i 's/apply_updates = no/apply_updates = yes/' /etc/dnf/automatic.conf
systemctl enable --now dnf-automatic.timer
;;
esac
echo "========================================="
echo " 基线初始化完成!请退出 root 登录并使用"
echo " ssh $ADMIN_USER@$HOSTNAME 重新登录"
echo "========================================="使用方法:
# 下载并审查脚本
curl -O https://example.com/scripts/baseline-init.sh
less baseline-init.sh
# 修改顶部参数后执行
sudo bash baseline-init.sh54.14 初始化后检查清单
完成初始化后,逐项验证:
# 1. 主机名
hostnamectl
# 2. 时区与时间同步
timedatectl status
chronyc tracking
# 3. 语言环境
localectl status
# 4. 系统版本与内核
cat /etc/os-release && uname -a
# 5. 管理员用户存在且可 sudo
sudo -l
# 6. SSH 只能密钥登录(不能密码登录 root)
ssh -o PubkeyAuthentication=no root@localhost # 应被拒绝
# 7. 防火墙规则
sudo ufw status verbose # Debian/Ubuntu
sudo firewall-cmd --list-all # RHEL/Fedora
# 8. fail2ban 运行中
systemctl status fail2ban
# 9. Swap 已启用
swapon --show && free -h
# 10. 监听端口(最简:仅 SSH)
sudo ss -tlnp | grep LISTEN
# 11. 自动更新已配置
systemctl status unattended-upgrades # Debian
systemctl status dnf-automatic.timer # RHEL
# 12. 检查 selinux/apparmor 状态
getenforce # RHEL
sudo aa-status # Ubuntu54.15 云平台初始化特殊考量
AWS EC2
# 检查 IMDSv2(Instance Metadata Service v2)
# AWS 推荐使用 IMDSv2 防止 SSRF
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/
# 安装 AWS CLI 及 SSM Agent
sudo apt install awscli -y
sudo snap install amazon-ssm-agentGCP
# GCP 账号和 SSH 密钥由 OS Login 管理
# 检查 guest agent
systemctl status google-guest-agent详见 28-系统安全加固与审计 中的更多安全基线配置。
54.16 本章总结
| 初始化步骤 | 关键命令 | 参考章节 |
|---|---|---|
| 主机名与时区 | hostnamectl set-hostname / timedatectl set-timezone | 本章 |
| NTP 时间同步 | chronyd 或 systemd-timesyncd | 本章 |
| 管理员账户 | useradd + ssh-copy-id | 23-SSH远程管理 |
| SSH 加固 | PermitRootLogin no | 23-SSH远程管理 |
| 防火墙 | ufw / firewalld | 24-防火墙与安全 |
| 防暴力破解 | fail2ban / sshguard | 28-系统安全加固与审计 |
| 自动更新 | unattended-upgrades / dnf-automatic | 本章 |
| Swap | fallocate + mkswap | 本章 |
| 监控代理 | netdata / node_exporter | 60-监控系统(Prometheus+Grafana) |