Skip to content

操作日志:设置服务器 ssh key 登录

1、目标服务器添加 公钥 ssh

sh
mkdir -p ~/.ssh

vim ~/.ssh/authorized_keys
text
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMGHoCP/r4RhUppntCddCDARXFX0pdUVlFYlKMFMuccS

可选权限处理

sh
chown -R deploy:deploy ~/.ssh

chmod 700 ~/.ssh

chmod 600 ~/.ssh/authorized_keys

2、本地电脑设置连接

sh
vim ~/.ssh/config
Host lab-staging
  HostName 10.9.0.177
  User qin
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes
  AddKeysToAgent yes
  ServerAliveInterval 30
  ServerAliveCountMax 3

UseKeychain yes 是 Mac 的配置

在本地验证一下,如:

ssh -o PasswordAuthentication=no aier

3、关闭ssh密码登录

sh
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

sudo vim /etc/ssh/sshd_config

# Ubuntu 24 以后 推荐使用独立配置文件
sudo vim /etc/ssh/sshd_config.d/00-local.conf

修改配置

sh
# 开启公钥登录
PubkeyAuthentication yes

# 关闭密码登录
PasswordAuthentication no

# 关闭 keyboard-interactive 登录
KbdInteractiveAuthentication no

# 禁止 root SSH 登录
PermitRootLogin no

检查 SSH 配置语法:

sh
sudo sshd -t
# 没有输出表示语法正常。

检查最终生效配置:

sh
sudo sshd -T | grep -E \
'pubkeyauthentication|passwordauthentication|kbdinteractiveauthentication|permitrootlogin'

# 预期:
# permitrootlogin no
# pubkeyauthentication yes
# passwordauthentication no
# kbdinteractiveauthentication no
sh
# 验证语法,空白表示没错
# sudo /usr/sbin/sshd -t
sudo sshd -t

sudo systemctl restart ssh

sudo systemctl status ssh

4、验证

打开新的终端测试:

sh
ssh aier

测试密码登录:

sh
ssh -o PubkeyAuthentication=no \
    -o PreferredAuthentications=password \
    aier