作为IT工程师,维护Linux服务器安全是核心任务。以下是经过实战验证的20个关键命令及其安全应用场景,附深度技巧:
# 检查特权账户(UID为0)
awk -F: '($3 == 0) {print $1}' /etc/passwd
# 查看sudo权限分配
grep -Po '^sudo.+:\K.*$' /etc/group | tr ',' '\n'
技巧:定期对比/etc/sudoers.d/
目录下文件的哈希值,使用sha256sum
建立基线
# 显示可疑进程树(含启动参数)
ps auxf | grep -E '(ncat|socat|\./)'
# 检测隐藏进程
diff <(ls /proc | sort -n) <(ps -eo pid | tail -n +2 | sort -n)
# 实时监控异常连接(显示地理位置)
ss -tunap | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | \
while read count ip; do
whois $ip | grep -i country;
done
# 快速阻断IP(iptables持久化)
iptables -A INPUT -s 192.168.1.100 -j DROP && \
iptables-save > /etc/iptables/rules.v4
# 建立关键目录的指纹库
find /bin /sbin /usr/bin /usr/sbin -type f -exec sha256sum {} + > /var/log/bin_hashes.log
# 自动化校验脚本(crontab每日运行)
while read -r hash file; do
if ! sha256sum --quiet -c <(echo "$hash $file"); then
echo "[ALERT] Modified: $file" | mail -s "HIDS Alert" admin@example.com
fi
done < /var/log/bin_hashes.log
# 提取SSH暴力破解特征
journalctl -u sshd | grep -E 'Failed|Invalid' | awk '{print $9}' | \
sort | uniq -c | sort -nr | head -20
# 检测webshell上传行为
find /var/www -type f -name "*.php" -exec grep -l 'eval($_POST' {} \;
# 检查密码策略
grep -E '^PASS_MAX_DAYS|^PASS_MIN_DAYS|^PASS_WARN_AGE' /etc/login.defs
# 验证内核防护
sysctl -a | grep -E 'kernel.randomize_va_space|kernel.exec-shield'
# 内存取证快速捕获
dd if=/dev/mem of=/tmp/mem.dump bs=1M count=100
# 可疑文件上传分析
file /tmp/uploaded_file
strings /tmp/uploaded_file | head -100
进阶技巧:
1. 使用auditd
框架记录关键系统调用:
auditctl -a always,exit -F arch=b64 -S execve -k process_creation
chattr
防止敏感文件被修改:chattr +i /etc/passwd /etc/shadow /etc/sudoers
useradd -s /bin/bash -m -p $(openssl passwd -1 'honeypot') attacker
#!/bin/bash
echo "[$(date)] Security Check Start"
rkhunter --check --sk
clamscan -r / --quiet -i --log=/var/log/clamav_scan.log
lynis audit system --quick
重要提醒:
- 所有审计命令建议通过script
命令记录操作日志
- 敏感操作使用sudo -i
切换到root环境而非直接root登录
- 关键结果通过gpg
加密后传输
这些命令需要根据实际环境调整参数,建议先在测试环境验证。安全运维的本质是建立"监控-防护-响应"的闭环体系,而非单纯依赖工具。