作为IT工程师,确保Linux服务器安全是首要任务。以下是我整理的20个关键安全命令及使用场景,附带深度技术解析:
一、用户与权限管理 1. 用户审计
cut -d: -f1 /etc/passwd | xargs -I {} id {}
awk -F: '($2 == "") {print $1}' /etc/shadow
find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null
grep -r "ALL=(ALL)" /etc/sudoers.d/
二、系统安全审计 3. 登录监控
last -ai | awk '!/wtmp/{print $1,$3,$10}'
tail -f /var/log/auth.log | grep --color -E 'fail|error|invalid'
find /etc -type f -exec sha256sum {} \; > /etc/.baseline_checksum
sha256sum -c /etc/.baseline_checksum 2>/dev/null | grep FAILED
三、网络防护 5. 防火墙深度配置
nft list ruleset 2>/dev/null || iptables -nvL --line-numbers
fail2ban-client status sshd
ss -tulnp | awk '!/State/{print $1,$5,$7}'
lsof -i -n | egrep "ESTABLISHED|SYN_SENT" | grep -v "localhost"
四、漏洞防护 7. 内核安全参数检查
cat /proc/sys/kernel/randomize_va_space # 应为2
lsmod | grep -E 'dccp|sctp|rds|tipc|nfc'
apt-get --just-print upgrade | grep security
yum update-minimal --security -y
五、应急响应 9. 恶意进程检测
ps -ef | awk '{print $2}' | sort | uniq > /tmp/ps_list ls /proc | grep -E '^[0-9]+$' | sort > /tmp/proc_list diff /tmp/ps_list /tmp/proc_list
pid=$(pgrep -f malicious_pattern) gcore -o /tmp/mal_dump $pid
高级技巧: 1. 使用auditd进行细粒度审计:
auditctl -w /etc -p wa -k etc_changes
{ echo "[$(date)] Security Check Start" # 检查项1:SSH配置 grep -E '^PermitRootLogin|^PasswordAuthentication' /etc/ssh/sshd_config # 检查项2:Cron异常任务 find /etc/cron* -type f -exec ls -la {} \; # 检查项3:可疑内核模块 lsmod | grep -Ev '^(Module|ext4|nfs|vbox)' } | tee -a /var/log/security_audit.log
注意事项: 1. 生产环境执行高危命令前务必测试 2. 建议通过跳板机操作,避免直接暴露管理端口 3. 敏感命令使用shred覆盖历史记录: shred -zu ~/.bash_history && history -c
安全是一个持续过程,建议建立定期检查机制(如每周自动化扫描+每月人工审计)。对于关键系统,建议部署OSSEC等HIDS进行实时监控。