git 使用ssh方式登录

git 服务器一般提供两种方式登录:

1 http 或https

2 SSH Keys

http 已经很熟悉了。 https 也类似就是配置一下证书即可。

SSH 协议登录呢?

之前也搞过。 今天总结一下:

首先, 在本地的用户目录创建 ssh 的非对称加密的秘钥对: 即公钥、私钥, 比如我本地目录是 C:\Users\lk\.ssh 

文件就是 id_rsa(私钥)和 id_rsa.pub (公钥)。 所谓公钥就是可以公开的 秘钥, 稍后呢, 是需要发给 git 服务器端的;  公钥它自然是 不受保护的.

创建的方式是:

ssh-keygen -t rsa -C 'abc@qq.com'

 -C  表示是注释,是comments,是可以随意填写的,当然,一般就使用登录的邮箱。当然, 也可以不填,不填默认是 用户名@主机名, 比如 luok@DESKTOP-G5S1KPQ

然后把 id_rsa.pub 即公钥的内容复制到git 服务器的 个人账户的ssh中,也就是添加到了 User Settings -> SSH Keys,  比如这个路径: http://192.169.2.234/profile/keys

 注意, 这里的title 默认是  id_rsa.pub 即公钥的最后一截。 其实仅仅是注释,是comments,是可以随意修改的。

测试过, 我们也可以添加多个SSH Key, git 客户端push 的时候,只要能使用其中一个SSH Key 登录, 那么就ok。 

 否则就还是会让你输入密码, 即使你密码正确,但是仍然让你一直输入:

luok@DESKTOP-G5S1KPQ MINGW64 /d/code/git/github (master)
$ git push origin master
git@192.169.2.234's password:
Permission denied, please try again.
git@192.169.2.234's password:
Permission denied, please try again.
git@192.169.2.234's password:
git@192.169.2.234: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

SSH 协议登录 原理

就是跟SSH 协议登录 shell 远程虚拟机是一样的。

如何切换登录协议?

还有就是,如果我们之前使用http 登录,现在想改成ssh,那么如何切换登录协议呢?  其实很简单,  git remote set-url 加 仓库的ssh地址即可。

注意,

仓库的ssh地址 格式是   git@git的ip地址:端口:项目组/项目名.git

仓库的http地址 格式是   http://git的ip地址:端口/项目组/项目名.git

ssh协议 前缀是git@, 后面分隔符是 冒号: ,http前缀是http://,后面分隔符是 斜杠/  ,

修改之前:

luok@DESKTOP-G5S1KPQ MINGW64 /d/code/git/github (master)
$ git remote -vv
origin http://192.169.2.234/luokai/redis.git (fetch)
origin http://192.169.2.234/luokai/redis.git (push)

修改:

$ git remote set-url origin git@192.169.2.234/luokai/redis.git

修改之后:

luok@DESKTOP-G5S1KPQ MINGW64 /d/code/git/github (master)
$ git remote -vv
origin git@192.169.2.234:luokai/redis.git (fetch)
origin git@192.169.2.234:luokai/redis.git (push)

 注意需要保证 仓库的ssh地址 的正确。 否则:

luok@DESKTOP-G5S1KPQ MINGW64 /d/code/git/github (master)
$ git push -u origin master
error: src refspec master does not match any
error: failed to push some refs to 'http://192.169.2.234/luokai/redis.git'

当然, 我们也可以直接添加仓库的ssh地址 作为远程地址,比如:

git remote add  mine git@192.169.2.23:luokai/aaa_deploy.git


版权声明
本文原创发表于 博客园,作者为 阿K .     本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。
欢迎关注本人微信公众号:觉醒的码农,或者扫码进群:

原文地址:https://www.cnblogs.com/FlyAway2013/p/15595043.html