VS code 密钥连接 Ubuntu 教程
VS code 密钥连接 Ubuntu 教程
只能将公钥上传服务器,将私钥保存至本地
生成密钥的方法
ssh-keygen -t rsa
在win下cmd
ssh-keygen.exe -t rsa
# 或者
ssh-keygen.exe -t rsa -C "maosql@vip.com"
# 或者
ssh-keygen -t rsa -C "maosql@vip.com"
- 通过
bash
命令行
ssh-keygen -t rsa
效果
[root@host ~]$ ssh-keygen <== 建立密钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <== 按 Enter
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): <== 输入密钥锁码,或直接按 Enter 留空
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:
0f:d3:e7:1a:1c:bd:5c:03:f1:19:f1:22:df:9b:cc:08 root@host
采用以上步骤之一会生成两个文件 id_rsa
(私钥) 和 id_rsa.pub
(公钥)
VS code 远程插件设置 ssh-key
点击 远程资源管理器
点击 SSH TARGETS
栏的配置图标 configure
,选择你目前生效的配置文件,添加上 IdentityFile
这个选项即可。例如:
ServerAliveInterval 60 # 每60秒发送信号用以保持连接
Host xxx.xxx.xxx.xxx
HostName xxx.xxx.xxx.xxx
User ubuntu
IdentityFile ~/.ssh/id_rsa # 私钥文件的位置
上传公钥文件至服务器
然后在本地下面路径找到这两个文件
# win
C:\Users\user\.ssh
# ubuntu
~/.ssh
id_rsa id_rsa.pub # 两个文件
然后把其中公钥文件拷贝到服务器的~/.ssh/authorized_keys
文件中,如果已经存在authorized_keys
文件则在尾部添加公钥文件内容,否则就创建authorized_keys
文件并复制公钥文件内容
或者也可以通过命令行上传公钥文件至服务器
ssh-copy-id -i ~/.ssh/id_rsa.pub username@ip
接着修改服务器的ssh
设置文件
修改/etc/ssh/sshd_config
文件
sudo vim /etc/ssh/sshd_config
采用AuthorizedKeysFile配置,启用authorized_keys
// 默认 # 注释掉的,后面一串删除改为yes
PermitRootLogin yes # 允许 root 账户通过 ssh 登录
RSAAuthentication yes # 使用 rsa 密钥验证,不过现在已经没有这项命令了
PubkeyAuthentication yes # 允许 ssh 登录通过 公钥登录
AuthorizedKeysFile .ssh/authorized_keys # 公钥认证文件位置
# 你可以把这个选项设置为 no 来关闭密码登录
# PasswordAuthentication yes
重新启动 ssh
systemctl restart sshd.service
坑点
权限问题。权限一定要按照下面来配置,不要想当然的配置成777
# 原因
# sshd为了安全,对属主的目录和文件权限有所要求。如果权限不对,则ssh的免密码登陆不生效。
# 用户权限700
chmod 700 /home/username
# .ssh权限
chmod 700 ~/.ssh
# ~/.ssh/authorized_keys权限
chmod 600 ~/.ssh/authorized_keys
试图写入的管道不存在
当服务器重装了系统后, IP 地址不变,再次进行远程连接时即会发生这个报错。观察错误日志可知这是因为服务器的指纹和本地存储的指纹不一致导致的。解决方案也很简单,更换服务器的 IP 地址或者删掉本地的 .ssh/known_hosts
文件即可。
参考
[1]: Win VScode免密登录ubuntu
[2]: ubuntu设置 SSH 通过密钥登录
[4]: Ubuntu 设置远程密钥登录