《服务器运维》模块一 · 第 1~3 讲学习记录
让第一台服务器学会自我防护
journalctl 查到了大量 failed 的登录失败记录,确认了暴力破解攻击的存在。# 查看登录失败记录
sudo journalctl -u sshd | grep -i "failed" | tail -30
# 新建普通用户并加入 wheel 组
sudo adduser liuhao
sudo usermod -aG wheel liuhao
# 生成密钥对(在自己电脑上,私钥绝不外传)
ssh-keygen -t ed25519 -C "liuhao-服务器加固"
# 安装公钥并设置权限
mkdir -p ~/.ssh
chmod 700 ~/.ssh
vi ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# 加固 sshd 配置后先测试语法再重载
sudo sshd -t
sudo systemctl reload sshd
# 主机防火墙放行 SSH
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
# 安装并启用 fail2ban
sudo dnf install -y epel-release fail2ban
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd
~/.ssh 目录权限不是 700、authorized_keys 不是 600 导致 SSH 静默拒绝,修正权限后解决。/var/log/secure 的写法不适用,改用 backend = systemd 后正常。让任何人输入域名都能访问到你的主页
@ 和 www 两条 A 记录,指向服务器公网 IP。mysite.conf,安全地让配置生效。index.html。# 安装并启动 Nginx
sudo dnf install -y nginx
sudo systemctl enable --now nginx
# 放行 HTTP
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload
# 准备网站目录
sudo mkdir -p /var/www/mysite
sudo chown -R liuhao:liuhao /var/www/mysite
sudo chmod 755 /var/www/mysite
# 编写站点配置后先测试再重载
sudo vi /etc/nginx/conf.d/mysite.conf
sudo nginx -t
sudo systemctl reload nginx
# 上传主页
scp index.html liuhao@服务器IP:/var/www/mysite/
# 排障:查看谁在读文件、看错误日志
ps -o user= -C nginx | sort -u
sudo tail -3 /var/log/nginx/mysite_error.log
nginx 用户运行,属于「其他人」无法读取。错误日志里 Permission denied 直接指了原因,改为 644 后恢复。记住:文件至少 644、目录至少 755。server_name 在起作用,IP 请求的 Host 匹配不上站点,落到默认站点处理,属正常现象。给网站加上安全锁
# 放行 HTTPS
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
# 安装 certbot 并先演练再正式申请
sudo dnf install -y certbot
sudo certbot certonly --webroot -w /var/www/mysite \
-d liuhao.cyou -d www.liuhao.cyou \
-m 邮箱 --agree-tos --no-eff-email --dry-run
sudo certbot certonly --webroot -w /var/www/mysite \
-d liuhao.cyou -d www.liuhao.cyou \
-m 邮箱 --agree-tos --no-eff-email
# 查看证书
sudo certbot certificates
# 80 端口跳转 + 443 提供内容,重载
sudo nginx -t
sudo systemctl reload nginx
# 启用续期定时器 + deploy 钩子
sudo systemctl enable --now certbot-renew.timer
sudo certbot renew --dry-run
curl 是 Invoke-WebRequest 的别名,要用 curl.exe 才能得到正确响应头。http:// 访问跳转到 HTTPS,二是证书续期仍需通过 80 端口验证,关掉三个月后证书就无法续期了。