𝑻𝒆𝒏𝑪𝒍𝒂𝒘正在头脑风暴···
𝑻𝒆𝒏𝑲𝒊𝑺𝒆𝒀𝒂の𝑨𝒈𝒆𝒏𝒕助手
𝑻𝒆𝒏-𝒇𝒍𝒂𝒔𝒉

Linux 服务器运维必备技能

Linux 服务器运维是 IT 基础设施管理的核心,掌握这些技能可以确保系统稳定、安全、高效运行。

系统基础

用户和权限管理

# 创建用户
sudo useradd -m -s /bin/bash username
sudo passwd username

# 修改用户
sudo usermod -aG sudo username # 添加到 sudo 组
sudo usermod -s /bin/zsh username # 修改 shell

# 删除用户
sudo userdel -r username

# 权限管理
sudo chmod 755 /path/to/directory
sudo chown user:group /path/to/file
sudo chown -R user:group /path/to/directory

# sudo 配置
sudo visudo
# 添加:username ALL=(ALL:ALL) NOPASSWD:ALL

系统监控

# 系统资源查看
top # 实时进程监控
htop # 增强版 top
free -h # 内存使用情况
df -h # 磁盘使用情况
du -sh /path/* # 目录大小统计

# 系统负载
uptime # 系统运行时间和负载
w # 当前登录用户
who # 在线用户列表

# 进程管理
ps aux # 查看所有进程
ps -ef | grep nginx # 查找特定进程
kill PID # 终止进程
killall process_name # 终止所有同名进程

网络配置

网络基础命令

# IP 地址管理
ip addr show # 查看网络接口
ip route show # 查看路由表
ping google.com # 网络连通性测试
traceroute google.com # 路由追踪

# 端口管理
netstat -tulpn # 查看监听端口
ss -tulpn # 更现代的 netstat
lsof -i :80 # 查看端口占用

# 防火墙配置
sudo ufw status # 查看 UFW 状态
sudo ufw enable # 启用防火墙
sudo ufw allow 22/tcp # 开放端口
sudo ufw deny 23/tcp # 关闭端口

Nginx 配置

# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
worker_connections 1024;
}

http {
# 基础配置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;

# Gzip 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript;

# 虚拟主机
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.html;

location / {
try_files $uri $uri/ =404;
}

# 反向代理
location /api {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
}

安全管理

SSH 安全配置

# 编辑 SSH 配置
sudo nano /etc/ssh/sshd_config

# 安全配置项
Port 2222 # 更改默认端口
PermitRootLogin no # 禁止 root 登录
PasswordAuthentication no # 禁用密码认证
PubkeyAuthentication yes # 启用密钥认证
AllowUsers username # 限制登录用户
MaxAuthTries 3 # 限制尝试次数

# 重启 SSH 服务
sudo systemctl restart sshd

防火墙配置

# UFW 基础规则
sudo ufw default deny incoming
sudo ufw default allow outgoing

# 开放必要端口
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 限制访问
sudo ufw allow from 192.168.1.0/24 to any port 22
sudo ufw deny from 203.0.113.0/24

# 启用防火墙
sudo ufw enable
sudo ufw status verbose

Fail2ban 防护

# 安装 Fail2ban
sudo apt install fail2ban

# 配置文件
sudo nano /etc/fail2ban/jail.local

[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3

[sshd]
enabled = true
port = 2222
logpath = /var/log/auth.log

[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log

# 启动服务
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

性能优化

系统优化

# 调整文件描述符限制
echo "* soft nofile 65536" >> /etc/security/limits.conf
echo "* hard nofile 65536" >> /etc/security/limits.conf

# 内核参数优化
echo "net.core.somaxconn = 65535" >> /etc/sysctl.conf
echo "net.ipv4.tcp_max_syn_backlog = 65535" >> /etc/sysctl.conf
echo "vm.swappiness = 10" >> /etc/sysctl.conf
sysctl -p

# 清理系统
sudo apt autoremove
sudo apt autoclean
sudo journalctl --vacuum-time=7d

数据库优化

# MySQL 配置优化
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 200
query_cache_size = 64M
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log

# 重启 MySQL
sudo systemctl restart mysql

自动化运维

定时任务

# 编辑 crontab
crontab -e

# 示例配置
# 每天凌晨 2 点备份数据库
0 2 * * * /usr/local/bin/backup_db.sh

# 每 15 分钟检查服务状态
*/15 * * * * /usr/local/bin/check_services.sh

# 每周清理日志
0 3 * * 0 find /var/log -name "*.log" -mtime +7 -delete

# 查看当前任务
crontab -l

# 查看执行日志
sudo tail -f /var/log/cron

监控脚本

#!/bin/bash
# /usr/local/bin/system_monitor.sh

# 系统负载检查
LOAD=$(uptime | awk -F'load average:' '{ print $2 }' | awk '{ print $1 }' | sed 's/,//')
if (( $(echo "$LOAD > 2.0" | bc -l) )); then
echo "High load: $LOAD" | mail -s "Server Alert" admin@example.com
fi

# 磁盘空间检查
DISK=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $DISK -gt 80 ]; then
echo "Disk usage: $DISK%" | mail -s "Server Alert" admin@example.com
fi

# 内存使用检查
MEM=$(free | awk 'NR==2{printf "%.2f", $3*100/$2}')
if (( $(echo "$MEM > 80" | bc -l) )); then
echo "Memory usage: $MEM%" | mail -s "Server Alert" admin@example.com
fi

备份脚本

#!/bin/bash
# /usr/local/bin/backup_db.sh

BACKUP_DIR="/backup/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="myapp_db"

# 创建备份目录
mkdir -p $BACKUP_DIR

# 备份数据库
mysqldump -u root -p$MYSQL_ROOT_PASSWORD $DB_NAME | gzip > $BACKUP_DIR/$DB_NAME_$DATE.sql.gz

# 删除 7 天前的备份
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete

# 上传到云存储
aws s3 cp $BACKUP_DIR/$DB_NAME_$DATE.sql.gz s3://my-backups/mysql/

echo "Backup completed: $BACKUP_DIR/$DB_NAME_$DATE.sql.gz"

日志管理

日志轮转

# 配置日志轮转
sudo nano /etc/logrotate.d/nginx

/var/log/nginx/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 644 nginx nginx
postrotate
systemctl reload nginx
endscript
}

日志分析

# 分析 Nginx 访问日志
sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# 统计 HTTP 状态码
sudo awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -nr

# 查找错误日志
sudo tail -f /var/log/nginx/error.log
sudo grep "error" /var/log/nginx/error.log

# 分析系统日志
sudo journalctl -u nginx -f
sudo journalctl --since "2024-01-01" --until "2024-12-31"

故障排除

常见问题排查

# 检查系统日志
sudo dmesg
sudo journalctl -xe

# 检查服务状态
sudo systemctl status nginx
sudo systemctl restart nginx

# 检查网络连接
sudo netstat -tulpn | grep :80
sudo ss -tulpn | grep :80

# 检查磁盘使用
sudo df -h
sudo du -sh /var/log

# 检查进程
ps aux | grep nginx
sudo kill -9 PID

性能分析

# CPU 使用情况
top -p $(pgrep nginx)
sudo mpstat 1 10

# 内存使用情况
free -m
cat /proc/meminfo

# 网络流量
sudo iftop
sudo nethogs

# 磁盘 I/O
sudo iotop
sudo iostat -x 1

安全加固

系统安全

# 更新系统
sudo apt update && sudo apt upgrade -y

# 安装安全工具
sudo apt install ufw fail2ban rkhunter chkrootkit

# 扫描恶意软件
sudo rkhunter --check
sudo chkrootkit

# 禁用不必要的服务
sudo systemctl disable apache2
sudo systemctl stop apache2

# 设置密码策略
sudo apt install libpam-pwquality
echo "minlen=8" >> /etc/security/pwquality.conf

[!tip]

  • 定期备份重要数据和配置文件
  • 使用密钥认证而不是密码认证
  • 监控系统日志及时发现异常
  • 保持系统和软件包最新版本

参考资料