SSH (Secure Shell) 是用于安全远程登录和管理Linux服务器的标准协议。以下是配置SSH服务器的详细步骤:
大多数Linux发行版默认安装了SSH服务器(通常是OpenSSH)。如果没有安装:
Debian/Ubuntu:
sudo apt update
sudo apt install openssh-server
RHEL/CentOS:
sudo yum install openssh-server
Arch Linux:
sudo pacman -S openssh
启动服务:
sudo systemctl start sshd
设置开机自启:
sudo systemctl enable sshd
检查服务状态:
sudo systemctl status sshd
主配置文件位于 /etc/ssh/sshd_config
。编辑前建议备份:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sudo nano /etc/ssh/sshd_config
更改默认端口 (减少自动化攻击):
Port 2222
禁用root登录 (安全最佳实践):
PermitRootLogin no
限制用户访问:
AllowUsers username1 username2
禁用密码认证 (仅使用密钥):
PasswordAuthentication no
启用公钥认证:
PubkeyAuthentication yes
ssh-keygen -t rsa -b 4096
ssh-copy-id -p [port] username@server_ip
或手动添加公钥到服务器的 ~/.ssh/authorized_keys
文件。
UFW (Ubuntu):
sudo ufw allow 22/tcp # 或您自定义的端口
sudo ufw enable
Firewalld (RHEL/CentOS):
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
修改配置后需要重启SSH服务:
sudo systemctl restart sshd
从另一台机器测试连接:
ssh -p [port] username@server_ip
使用Fail2Ban 防止暴力破解:
sudo apt install fail2ban # Debian/Ubuntu
sudo yum install fail2ban # RHEL/CentOS
配置两因素认证 (2FA) 增加安全性
设置空闲超时:
ClientAliveInterval 300
ClientAliveCountMax 2
限制IP访问 (如果可能)
禁用不安全的加密算法:
KexAlgorithms curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
sshd_config
中的认证设置/var/log/auth.log
(Debian/Ubuntu) 或 /var/log/secure
(RHEL/CentOS)通过以上步骤,您应该能够安全地配置Linux SSH服务器。根据您的具体安全需求,可以进一步调整配置参数。