目录
本文基于 Ubuntu 22.04 LTS
(openssh-server < 1:9.0p1-1ubuntu1
) 版本。
安装 OpenSSH Server
通常情况下,常用的 Linux 发行版在系统部署阶段都可以选择安装 OpenSSH Server,如果没有安装,可以通过包管理器安装。
sudo apt updatesudo apt install openssh-server
sudo yum install openssh-server
配置文件
配置文件路径
/etc/ssh/sshd_config
:OpenSSH Server 配置文件/etc/ssh/sshd_config.d/*.conf
:推荐的用户配置文件目录
常用配置项
配置项 | 说明 | 默认值 |
---|---|---|
Port | SSH 服务监听端口 | 22 |
PermitRootLogin | 是否允许 root 用户登录 | prohibit-password |
PasswordAuthentication | 是否允许密码登录 | yes |
MaxAuthTries | 最大尝试次数 | 6 |
MaxSessions | 最大会话数 | 10 |
PubkeyAuthentication | 是否允许公钥登录 | yes |
PasswordAuthentication | 是否允许密码登录 | yes |
KbdInteractiveAuthentication | 是否允许键盘交互式认证 | yes |
UsePAM | 是否使用 PAM 模块 | yes |
PrintMotd | 是否显示登录信息 | yes |
SysLogFacility | 日志设施 | AUTH |
LogLevel | 日志级别 | INFO |
配置密钥登录(与禁用密码登录)
生成密钥对
ssh-keygen -t rsa -b 4096 -C "name@example.com"
根据交互式终端可以选择修改生成位置,添加私钥密码锁。
Generating public/private rsa key pair.Enter file in which to save the key (/home/name/.ssh/id_rsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /home/name/.ssh/id_rsaYour public key has been saved in /home/name/.ssh/id_rsa.pubThe key fingerprint is:SHA256:u4Y6/xXU8wi7DHmiZLEFozRI7JjyX+I7nG12mf/RK/o name@machineThe key's randomart image is:+---[RSA 4096]----+| o..o o || o. o o . || + . . . o o ||+ . + o o + ||.. + S + . . || . .o.. * o . || + =...o+ . . || B = =o .. . || oO.+o.o+E.. |+----[SHA256]-----+
如果在服务端进行这一步,密钥对会生成在 ~/.ssh
目录下。使用 RSA 算法时默认输出的文件是 id_rsa
(私钥) 和 id_rsa.pub
(公钥)。
如果在客户端进行,则需要将生成的公钥文件传输到服务端。
安装公钥
将公钥传输到所需服务器的 ~/.ssh
目录中。然后导入到 authorized_keys
文件中。
ls ~/.ssh# authorized_keys id_rsa id_rsa.pub known_hostscat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
sshd_config
# 修改端口# 别忘了开放修改的防火墙端口。Port 12345
# 启用公钥登录PubkeyAuthentication yes# 安全性配置PermitRootLogin noMaxAuthTries 3
修改完后重启 sshd
服务。使用密钥登录一次确认无误后,再禁用密码登录。
# 禁用密码登录PasswordAuthentication no## 需要同时关闭交互式密码验证和 PAM 模块,否则仍然可以使用密码登录KbdInteractiveAuthentication noUsePAM no