在 Linux 虚拟机中安装和配置 SSH 服务器(OpenSSH Server)是一个常见的网络服务配置任务。以下是安装和配置 SSH 服务器的详细步骤,适用于大多数 Linux 发行版(如 Ubuntu、CentOS、Debian 等)。
✅ 一、安装 OpenSSH 服务器
1. 在 Ubuntu/Debian 系统中:
sudo apt update
sudo apt install openssh-server
2. 在 CentOS/RHEL 系统中:
sudo yum install openssh-server
✅ 二、启动 SSH 服务
1. 启动 SSH 服务:
sudo systemctl start ssh
2. 设置开机自启:
sudo systemctl enable ssh
✅ 三、配置 SSH 服务器
1. 修改 SSH 配置文件
1.1 文件位置:
/etc/ssh/sshd_config
1.2 常见配置项:
| 配置项 | 说明 |
|---|---|
Port 22 |
设置 SSH 端口(默认是 22) |
PermitRootLogin yes |
允许 root 用户登录(不推荐,生产环境慎用) |
PasswordAuthentication yes |
允许密码认证 |
Banner /path/to/banner.txt |
设置登录提示信息 |
UsePAM yes |
启用 PAM 认证(推荐) |
1.3 修改配置文件:
sudo nano /etc/ssh/sshd_config
修改以下内容(根据需要):
Port 22
PermitRootLogin no
PasswordAuthentication no
UsePAM yes
保存并退出(Ctrl + X,然后 Y 确认保存)。
✅ 四、启动并检查 SSH 服务
sudo systemctl start ssh
sudo systemctl status ssh
✅ 五、测试 SSH 连接
1. 从另一台机器连接:
ssh username@your_virtual_machine_ip
2. 如果是 Ubuntu/Debian:
ssh username@192.168.1.100
3. 如果是 CentOS/RHEL:
ssh username@192.168.1.100
✅ 六、防火墙配置(推荐)
1. Ubuntu/Debian:
sudo ufw allow 22
sudo ufw enable
2. CentOS/RHEL:
sudo systemctl enable firewalld
sudo firewall-cmd --permanent --add-port=22/tcp
sudo firewall-cmd --reload
✅ 七、安全建议
- 禁用 root 登录:
PermitRootLogin no - 使用 PAM 认证:
UsePAM yes - 限制用户登录:
AllowUsers username1 username2 - 设置密钥认证:推荐使用 SSH 密钥认证,避免密码泄露
- 定期更新系统:
sudo apt update && sudo apt upgrade
✅ 八、其他可选配置
- 设置 SSH 登录提示:
Banner /path/to/banner.txt - 限制登录 IP:在
sshd_config中设置AllowUsers或DenyHosts - 使用 SSH 端口转发:在客户端使用
ssh -L 8080:localhost:22 user@vm_ip
✅ 总结
| 步骤 | 命令 |
|---|---|
| 安装 SSH 服务 | sudo apt install openssh-server(Ubuntu/Debian) |
| 启动 SSH 服务 | sudo systemctl start ssh |
| 设置开机自启 | sudo systemctl enable ssh |
| 修改配置文件 | sudo nano /etc/ssh/sshd_config |
| 检查服务状态 | sudo systemctl status ssh |
| 测试连接 | ssh username@your_vm_ip |
如需进一步配置 SSH 登录方式(如密钥认证、端口转发等),可以继续提问!
