PyCharm在使用ssh-key免密码登陆跳板机及服务器后的设置

折腾了两三天,本来想偷个懒,设置个免密登陆跳板机和服务器,直接一键ssh的,结果发现PyCharm死活无法设置好,代码无法同步。查询几天后,终于找到了解决办法,其中比较有用的两个链接如下:
https://zhuanlan.zhihu.com/p/53792195
https://blog.csdn.net/github_28260175/article/details/100012157
我也把我的整个过程记录如下:

本地机器及跳板机设置

第1步

位置:本地机器;目标:生成公钥、私钥。

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/username/.ssh/id_rsa):
/Users/username/.ssh/id_rsa already exists.
Overwrite (y/n)?

上面的选项可以直接不管,按 enter 即可

第2步

位置:本地机器 ⟶ 跳板机;目标:将公钥传送给跳板机,即将生成的 id_rsa.pub 中的内容传递给跳板机;

$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@跳板机ip (将 ip 替换为你的跳板机 ip)
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@跳板机ip's password:(此处输入对应跳板机的登陆密码)
Number of key(s) added:        1
Now try logging into the machine, with:   "ssh 'root@跳板机ip'"
and check to make sure that only the key(s) you wanted were added.

第3步

位置:本地机器 ⟶ 跳板机;目的:将 id_rsa 和 id_rsa.pub 传送给跳板机

scp -r ~/.ssh/id_rsa* 服务器ip: (注意:服务器ip后面有个冒号“:”)

第4步

位置:跳板机;目的:在跳板机上生成 ssh key,并传送给目标服务器
首先登陆跳板机:

ssh 跳板机ip

在跳板机上生成公钥私钥:

ssh-keygen -t rsa

将生成的公钥传送给目标服务器:

ssh-copy-id -i ~/.ssh/id_rsa.pub 目标服务器ip

在跳板机上,将从本地机器传来的公钥,传送给目标服务器:

ssh-copy-id -i id_rsa.pub 目标服务器ip

至此,目标服务器上已经有了本地机器,及跳板机的公钥,且跳板机也拥有了本地机器的公钥。

第5步

位置:本地机器;目标:配置 ssh 下的 config 文件;

vi ~/.ssh/config

如果不存在 config 文件,用 touch 命令创建一个再打开即可:

touch ~/.ssh/config

在 config 文件中填入以下内容:

Host jumpserver(跳板机的名字,随便起)
    HostName 跳板机ip
    User 跳板机登陆名
    Port 22

Host targetserver (服务器的名字,也随便起)
    HostName 服务器ip
    User 服务器登陆名
    Port 22
    ProxyCommand ssh -q -W %h:%p jumpserver(跳板机的名字,与上面的保持一致)

保存好并退出,测试一下即可:

ssh targetserver

至此,从本地机器,通过跳板机,到目标服务器的免密登陆,设置完成。

PyCharm 设置

第1步

先进行隧道转发:

ssh -N -f -L 6000(可换到任意端口):服务器ip>:22(服务器端口) -p 22(跳板机端口) 跳板机登陆名(登录跳板机的用户名)@跳板机ip -o TCPKeepAlive=yes

举个例子如下:

ssh -N -f -L 6000:129.0.0.0:22 -p 22 ttppss@128.0.0.0 -o TCPKeepAlive=yes
6000 是我使用的本地端口,129.0.0.0 是目标服务器的 ip 地址,我在服务器的端口和跳板机的端口都设为了 22,ttppss 是我登陆跳板机的用户名,128.0.0.0 是跳板机的 ip 地址。

第2步

在 Tools 下选择 Deployment ⟶ Configuration 在这里插入图片描述
点击左上角加号“+”,新建连接,选择 SFTP,点击 SSH configuration 右侧的 … 打开窗口
在这里插入图片描述
下图中 Host 就填 localhost,端口填上面隧道转发时指定的端口,我用的是6000. Username 是登陆目标服务器的用户名。Authentication type 选 Key pair,并在下面的 private key file 中选择本地机器生成的 id_rsa 文件,点击 Apply 保存就行。
在这里插入图片描述

全文结束

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值