Linux SSH 登录配置
2025年2月18日大约 3 分钟
粗略记录一下 Linux SSH 登录的一些常用配置。本文基于 Ubuntu 22.04 LTS
(openssh-server < 1:9.0p1-1ubuntu1
) 版本。
安装 OpenSSH Server
通常情况下,常用的 Linux 发行版在系统部署阶段都可以选择安装 OpenSSH Server,如果没有安装,可以通过包管理器安装。
Debian/Ubuntu
sudo apt update
sudo apt install openssh-server
CentOS/RHEL
sudo yum install openssh-server
配置文件
提示
从 Ubuntu 22.10
(openssh-server 1:9.0p1-1ubuntu1
) 开始,OpenSSH Server 默认配置为使用 systemd socket
激活,服务名从 sshd
修改成了 ssh
。因此监听就转交给了 ssh socket
,服务本身不再监听端口。如果需要修改监听端口,需要修改 ssh.socket
的配置。
https://discourse.ubuntu.com/t/sshd-now-uses-socket-based-activation-ubuntu-22-10-and-later/30189
配置文件路径
/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 "[email protected]"
根据交互式终端可以选择修改生成位置,添加私钥密码锁。
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_rsa
Your public key has been saved in /home/name/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:u4Y6/xXU8wi7DHmiZLEFozRI7JjyX+I7nG12mf/RK/o name@machine
The 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_hosts
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
下载私钥
如果在服务端完成密钥对生成,可以将私钥下载到客户端。
sshd_config
# 修改端口
# 别忘了开放修改的防火墙端口。
Port 12345
# 启用公钥登录
PubkeyAuthentication yes
# 安全性配置
PermitRootLogin no
MaxAuthTries 3
修改完后重启 sshd
服务。使用密钥登录一次确认无误后,再禁用密码登录。
# 禁用密码登录
PasswordAuthentication no
## 需要同时关闭交互式密码验证和 PAM 模块,否则仍然可以使用密码登录
KbdInteractiveAuthentication no
UsePAM no