检查权限
确保你有管理员权限,因为配置和管理SSH服务器通常需要root权限,你可以使用sudo命令来执行相关操作。
安装SSH服务器
根据你的系统类型安装OpenSSH服务器:
- 在Ubuntu/Debian系统上:
sudo apt-get update && sudo apt-get install openssh-server
- 在 CentOS/RHEL系统上:
sudo yum install openssh-server
生成SSH认证文件
创建SSH认证文件(optional):
- 生成私钥和公钥:
sudo -u nobody ssh-keygen -t rsa -b 4096
这将生成
id_rsa(私钥)和id_rsa.pub(公钥),放在~/.ssh目录下。
配置SSH服务器
编辑sshd_config文件:
-
打开文件:
sudo nano /etc/ssh/sshd_config
-
设置默认配置:
- 打开22端口:
Port 22
- 允许端口转换:
AllowPortForwarding yes
- 启用DNS:
UseDNS yes
- 启用Ciphers:
Ciphers aes256-ctr,aes192-ctr,rijndael-aes256@openssh.com
- 打开22端口:
-
设置认证策略:
- 允许使用公钥:
PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys
- 禁止密码登录:
PasswordAuthentication no
- 设置默认登录策略(可选):
ChallengeKeyExchange yes
- 允许使用公钥:
-
设置访问控制列表(可选):
AllowGroups wheel sshd
或者,限制访问:
PermitRootLogin no
-
保存并退出编辑器: 按下
Ctrl+O,然后输入exit。
启用SSH服务器
启动并设置开机启动:
- 启动服务:
sudo systemctl start sshd
- 设置开机启动:
sudo systemctl enable sshd
配置防火墙(可选)
确保防火墙允许SSH端口:
-
在iptables中添加规则(如果使用iptables):
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT sudo service iptables save sudo service iptables restart
-
在firewalld中配置(CentOS/RHEL 7+):
sudo firewall-cmd --permanent --add-service=ssh sudo firewall-cmd --permanent --add-port=22/tcp sudo firewall-cmd --reload
生成SSH手册(可选)
创建一个HTML文件作为用户指南:
sudo nano /usr/share/doc/openssh/server manual.html
并保存后,上传到服务器。
测试配置
- 本地测试:
ssh -p 22 localhost
- 远程测试:
从另一台机器登录:
ssh -p 22 <服务器IP>
验证日志
查找错误信息:
sudo tail -f /var/log/auth.log
注意事项
- 权限:确保
/etc/ssh和~/.ssh目录权限正确。 - 私钥:确保私钥和公钥正确配对。
- 端口:监控22端口,确保没有被阻止。
额外配置(可选)
- 启用GSSAPI:
UseGSSAPI yes
- 设置键环:
Enable KeyboardInteractiveAuthentication yes
通过以上步骤,你应该能够成功配置并管理一个安全的SSH服务器,确保定期更新并监控服务器状态,以保持高安全性。
