快速添加SSH公钥进行免密登录
source link: https://qq52o.me/2828.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在需要连接其他人服务器或者其他的场景下,忘记密码或者不方便提供密码的时候可以通过 SSH 免密码进行登录。
生成 SSH 密钥
首先需要一个 SSH 密钥,已经有了的可以跳过。
ssh-keygen -t ed25519 -C "[email protected]"
如果你使用的是不支持 Ed25519
算法的旧系统,请使用以下命令:
ssh-keygen -t rsa -b 4096 -C "[email protected]"
默认可以一路回车,生成后会在 ~/.ssh/
目录下生成 id_ed25519
、id_ed25519.pub
或者 id_rsa
、id_rsa.pub
两个密钥文件。
复制公钥到远程主机
需要将公钥复制到远程主机上,以便进行身份验证。有下面几种命令:
ssh-copy-id username@remote_host
ssh-copy-id
这种方式需要知道服务器的密码,不知道密码时不能使用。
这样的话就只能手动将 ~/.ssh/id_rsa.pub
/~/.ssh/id_ed25519.pub
公钥文件内容复制,并添加到服务器账户的 ~/.ssh/authorized_keys
文件里。
当需要告诉不同的用户公钥文件,每次分发也是一个问题,但是 GitHub 可以直接显示用户配置的 SSH 和 GPG Keys。
比如我的 GitHub 账号是:sy-records
可以通过 https://github.com/sy-records.keys 获取到我的 SSH 公钥;
通过 https://github.com/sy-records.gpg 获取到我的 GPG 公钥。
这样只需要发一个地址,让对应的用户获取到公钥,把获取到的公钥加到服务器账户的 ~/.ssh/authorized_keys
文件里面,
如果服务器是 Debian 或者 Ubuntu,可以安装 ssh-import-id
来导入 GitHub 上的公钥:
# 推荐使用这个来进行导入
apt install ssh-import-id
ssh-import-id-gh username
# 添加我的公钥
ssh-import-id-gh sy-records
有所不同的是这个命令用的是 GitHub 的开放接口:https://api.github.com/users/sy-records/keys
但是本质上都是把公钥下载下来加入到 ~/.ssh/authorized_keys
这个文件中。
也可以通过下载 https://api.github.com/users/<username>/keys
,到 ~/.ssh/authorized_keys
wget -O https://api.github.com/users/sy-records/keys | tee -a ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
配置完成以后就可以通过 ssh 测试能否无需密码正常连接服务器了。
ssh username@remote_host
ssh username@remote_host -pport
等操作完成,再把添加的内容删掉,这样就不能再次登录了。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK