一、生成密钥对
在服务器内执行
ssh-keygen
将会输出以下内容
Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): #回车 Enter passphrase (empty for no passphrase): #设置密钥密码,可以直接回车设置为空 Enter same passphrase again: #再次输入密钥密码,可以直接回车设置为空 Your identification has been saved in /root/.ssh/id_rsa Your public key has been saved in /root/.ssh/id_rsa.pub The key fingerprint is: SHA256:yGaLYUNe8ZjUpK6l8Xgi16MTHnPrEH0wmfQaBMVnfOs root@sztu The key's randomart image is: +---[RSA 3072]----+ | .+*+. | | +.X= . | | . @oo. . | | o = * . | | B X S. | | .+/.o E | | ..O=*. | | oo=.. | | .o. | +----[SHA256]-----+
密钥密码设置后,在私钥使用时需要使用密码才能登陆,留空可以直接实现证书无密码登陆。
二、安装公钥
刚才创建的密钥对都存在于 ~/.ssh 中,即当前用户文件夹下的 .ssh。
执行以下命令安装证书
cat id_rsa.pub >> authorized_keys
配置权限
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh
三、配置 SSH 密钥登录
编辑 /etc/ssh/sshd_config
vi /etc/ssh/sshd_config
解除或添加 PubkeyAuthentication yes
,并设置 PasswordAuthentication no
禁止密码登录 ssh
重启 ssh 服务
systemctl restart sshd
四、本地配置服务器登录
本文以 macOS 为例,将服务器上 ~/.ssh/id_rsa
下载到本地,保存在本地的 ~/.ssh/id_rsa
并设置权限
chmod 600 id_rsa
并在 ~/.ssh/config
中写入
Host 自定义服务器的名称
HostName 服务器的 ip
Port 服务器 ssh 的端口,默认为22
User 登录的用户名
IdentityFile ~/.ssh/id_rsa (私钥路径)
这样就可以直接通过 ssh 自定义服务器的名称
登录到服务器上了。
评论 (0)