生成密钥

命令:

ssh-keygen -t ed25519

现在更推荐使用 ed25519 而不是 rsa

生成的私钥以 .pub 结尾,内容类似如下:

ssh-ed25519 AAA......Hp3 [用户名@hostname]

部署公钥 (使用 ssh-copy-id)

ssh-copy-id 是一个自动化的脚本,它会将你的公钥追加到远程服务器的 ~/.ssh/authorized_keys 文件中,并自动设置正确的文件权限(目录权限 700,文件权限 600),避免了手动复制和修改权限的繁琐步骤。

在客户端(你的电脑)执行以下命令:

# 语法:ssh-copy-id -i [公钥文件路径] [用户名@服务器IP]
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@hostname

执行后,输入一次服务器的用户密码即可完成部署。


调整 openSSH 选项

root 身份打开 /etc/ssh/sshd_config ,更改以下几项:

PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no

或者直接使用 sed 命令来修改:

sudo sed -i -E 's/^#?(PermitRootLogin|PasswordAuthentication)[[:space:]]+.*/\1 no/; s/^#?PubkeyAuthentication[[:space:]]+.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config

重启 sshd 服务

sudo systemctl restart sshd.service

在有些服务器中,可能会叫作 ssh.service。这时候你需要重启 ssh.service 而不是 sshd.service


Windows 设置

打开 .ssh/ 文件夹下的 config 文件,添加类似如下内容

Host tx   #别名
	User [Your User ID]   #登陆用户名
	Hostname {Your Server IP or Address}   #服务器地址
	PreferredAuthentications publickey   #使用密钥登陆
	IdentityFile C:\Users\[用户]\.ssh\id_ed25519   #私钥地址