LeiTao
LeiTao
发布于 2026-10-10 / 24 阅读
0
0

Linux 服务器运维常用命令速查

Linux 服务器运维常用命令

一、系统信息

查看系统基本信息

# 系统版本
cat /etc/os-release
uname -a

# 运行时间与负载
uptime

# 磁盘使用情况
df -h
df -h --total

# 目录占用大小
sudo du -sh /var/*
sudo du -sh /* | sort -rh | head -10

# 内存使用
free -h
cat /proc/meminfo

# CPU 信息
lscpu
nproc

二、进程管理

查看进程

# 查看所有进程
ps aux
ps aux | grep nginx

# 实时监控
top
htop   # 更友好的界面

# 按资源排序
ps aux --sort=-%cpu | head -10   # CPU 占用前 10
ps aux --sort=-%mem | head -10   # 内存占用前 10

杀死进程

kill -9 <PID>          # 强制终止
kill -15 <PID>         # 优雅终止
killall nginx          # 按名称终止
pkill -f "dotnet.*MyApp"

三、网络管理

端口与连接

# 查看监听端口
ss -tlnp
ss -tlnp | grep :80

# 查看所有连接
ss -an

# 网络接口
ip addr
ip route

# 测试连通性
ping -c 4 8.8.8.8
traceroute example.com

# 下载文件
wget https://example.com/file.tar.gz
curl -O https://example.com/file.tar.gz

防火墙(UFW)

sudo ufw status verbose
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 enable

四、文件与目录操作

查找文件

# 按名称查找
find /var/log -name "*.log" -type f

# 按时间查找(7天内修改的文件)
find /var/log -name "*.log" -mtime -7

# 按大小查找(大于100MB)
find / -type f -size +100M 2>/dev/null

# 快速查找(需要 updatedb)
locate nginx.conf

文件权限

chmod 755 script.sh
chmod +x script.sh          # 添加执行权限
chown www-data:www-data /var/www/myapp -R

压缩与解压

tar -czvf archive.tar.gz /path/to/dir    # 压缩
tar -xzvf archive.tar.gz                  # 解压
tar -xzvf archive.tar.gz -C /target/dir   # 解压到指定目录

zip -r archive.zip /path/to/dir
unzip archive.zip -d /target/dir

五、日志管理

查看日志

# 实时查看
tail -f /var/log/syslog
journalctl -u nginx -f          # 查看 systemd 服务日志

# 查看最近 100 行
tail -n 100 /var/log/syslog

# 搜索关键词
grep "ERROR" /var/log/syslog
grep -i "error" /var/log/syslog | tail -20

# 按时间范围
journalctl --since "2024-01-01" --until "2024-01-02" -u nginx

日志轮转(logrotate)

# 查看轮转配置
cat /etc/logrotate.d/nginx

# 手动触发轮转
sudo logrotate -f /etc/logrotate.d/nginx

六、定时任务

Crontab

# 编辑当前用户的 crontab
crontab -e

# 查看当前用户的 crontab
crontab -l

Cron 表达式格式:

┌───────── 分钟 (0-59)
│ ┌─────── 小时 (0-23)
│ │ ┌───── 日 (1-31)
│ │ │ ┌─── 月 (1-12)
│ │ │ │ ┌─ 星期 (0-6, 0=周日)
│ │ │ │ │
* * * * *  command

常见示例:

# 每天凌晨 2 点备份
0 2 * * * /opt/backup.sh

# 每 5 分钟检查
*/5 * * * * /opt/check.sh

# 每周日凌晨重启
0 4 * * 0 /sbin/reboot

七、性能排查

CPU

# 查看负载趋势
uptime
sar -u 1 5          # 5次采样,间隔1秒

# 查看高 CPU 进程
top -o +%CPU | head -20

内存

free -m
vmstat 1 5

磁盘 IO

iostat -x 1 5
dd if=/dev/zero of=/tmp/testfile bs=1M count=500 oflag=direct  # 写入测试

综合监控

# 一键查看系统状态
sudo apt-get install -y sysstat
sar -A | head -50

# 网络流量
vnstat -h

八、安全检查

# 查看最近登录
last -20
lastb -20          # 失败的登录

# 查看当前登录用户
w
who

# 检查 SSH 配置
sudo grep -E "^(PermitRootLogin|PasswordAuthentication|Port)" /etc/ssh/sshd_config

# 检查 sudo 用户
cat /etc/sudoers | grep -v "^#" | grep -v "^$"

# 检查定时任务
ls -la /etc/cron.d/
crontab -l -u root

提示:建议在日常运维中建立自动化监控(如 Prometheus + Grafana),将上述命令编排成巡检脚本定期执行,异常时自动告警。


评论