作为IT工程师,确保Linux服务器的安全性是至关重要的任务。以下是一系列关键命令和最佳实践,可帮助您维护和监控服务器安全。
# 查看所有用户
cat /etc/passwd
# 查看有登录权限的用户
grep -v "/sbin/nologin" /etc/passwd | grep -v "/bin/false"
# 检查空密码账户
awk -F: '($2 == "") {print}' /etc/shadow
# 查看sudo权限用户
grep -Po '^sudo.+:\K.*$' /etc/group
# 查看用户组成员
groups username
# 修改文件权限
chmod 750 sensitive_file # 所有者:rwx, 组:r-x, 其他:---
chown root:root sensitive_file
# 查看最近登录记录
last
# 查看失败登录尝试
lastb
# 查看当前登录用户
who
# 查看运行中的进程
ps aux
# 查看网络连接
netstat -tulnp
ss -tulnp
# 查找异常进程
top -c
htop
# 查找SUID/SGID文件
find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null
find / -perm -2000 -type f -exec ls -la {} \; 2>/dev/null
# 查找可写文件
find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print
find / -xdev -type f \( -perm -0002 -a ! -perm -1000 \) -print
# 查找无主文件
find / -xdev \( -nouser -o -nogroup \) -print
# 创建重要文件的哈希值
sha256sum /etc/passwd /etc/shadow /etc/group > /root/file_hashes.txt
# 定期检查
sha256sum -c /root/file_hashes.txt
# iptables (传统)
iptables -L -n -v
# nftables (较新系统)
nft list ruleset
# firewalld (CentOS/RHEL)
firewall-cmd --list-all
# 检查SSH配置
cat /etc/ssh/sshd_config | grep -v "^#" | grep -v "^$"
# 推荐的SSH配置:
# Port 2222 (非标准端口)
# PermitRootLogin no
# PasswordAuthentication no (使用密钥认证)
# MaxAuthTries 3
# 认证日志
tail -f /var/log/auth.log # Debian/Ubuntu
tail -f /var/log/secure # RHEL/CentOS
# 系统日志
journalctl -xe # systemd系统
# 查找失败登录尝试
grep "Failed password" /var/log/auth.log | awk '{print $9}' | sort | uniq -c | sort -nr
# 查找暴力破解尝试
grep "BREAK-IN ATTEMPT" /var/log/auth.log
# 实时监控日志
tail -f /var/log/syslog | grep -i "error\|fail\|warning"
# Debian/Ubuntu
apt update && apt upgrade -y
apt list --upgradable
# RHEL/CentOS
yum update -y
yum check-update
# 自动安全更新 (Ubuntu)
unattended-upgrades --dry-run --debug
# 安装
apt install lynis # Debian/Ubuntu
yum install lynis # RHEL/CentOS
# 运行扫描
lynis audit system
# 安装rkhunter
apt install rkhunter # Debian/Ubuntu
yum install rkhunter # RHEL/CentOS
# 运行检查
rkhunter --check --sk
# 检查cron任务
crontab -l
ls -la /etc/cron*
# 检查启动项
systemctl list-unit-files --type=service | grep enabled
ls -la /etc/init.d/
# 检查内核模块
lsmod
通过熟练掌握这些命令和最佳实践,您可以显著提高Linux服务器的安全性,并能够快速识别和响应潜在的安全威胁。