禁用密码登录,使用SSH密钥对认证:
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo systemctl restart sshd
使用强密钥(至少4096位RSA或Ed25519):
ssh-keygen -t ed25519 -a 100 # 或 ssh-keygen -t rsa -b 4096
bash
sudo apt install libpam-google-authenticator
google-authenticator
# 然后在/etc/pam.d/sshd添加:
auth required pam_google_authenticator.so
使用sudo
而非直接root登录:
sudo visudo
# 添加:username ALL=(ALL:ALL) ALL
限制sudo命令范围(如仅允许特定命令):
username ALL=(ALL) NOPASSWD: /usr/bin/apt update, /usr/bin/apt upgrade
bash
sudo ufw allow ssh
sudo ufw enable
修改默认端口并限制访问:
sudo sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config
sudo ufw allow 2222/tcp
限制root登录和用户访问:
echo "PermitRootLogin no" | sudo tee -a /etc/ssh/sshd_config
echo "AllowUsers username" | sudo tee -a /etc/ssh/sshd_config
bash
echo "export TMOUT=300" | sudo tee -a /etc/profile # 300秒=5分钟
启用详细日志:
echo "LogLevel VERBOSE" | sudo tee -a /etc/ssh/sshd_config
安装并配置auditd:
sudo apt install auditd
sudo auditctl -a always,exit -F arch=b64 -S execve
bash
echo 'export HISTTIMEFORMAT="%F %T "' >> ~/.bashrc
echo 'export HISTSIZE=10000' >> ~/.bashrc
echo 'export HISTFILESIZE=10000' >> ~/.bashrc
bash
sudo apt install aide
sudo aideinit
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
bash
(crontab -l ; echo "0 3 * * * /usr/bin/aide --check") | crontab -
bash
sudo pkill -u username sshd
bash
sudo passwd -l username
tmux
或screen
保持会话,避免网络中断导致操作中断--dry-run
参数测试破坏性命令通过实施这些措施,您可以显著提高通过命令行操作Linux服务器时的安全性,降低被入侵或误操作的风险。