Git创建和公钥生成

来源:互联网 发布:linux中socket通信 编辑:程序博客网 时间:2024/05/22 07:35
Git 创建
Username

First you need to tell git your name, so that it can properly label the commits you make.

git config --global user.name "Your Name Here"
# Sets the default name for git to use when you commit

Email

Git saves your email address into the commits you make. We use the email address to associate your commits with your GitHub account.

git config --global user.email "your_email@example.com"
# Sets the default email for git to use when you commit

Your email address for Git should be the same one associated with your GitHub account. If it is not, see this guide for help adding additional emails to your GitHub account. If you want to keep your email address hidden, this guide may be useful to you.
补充:可直接打开.gitconfig文件修改username和 email
公钥生成
GitHub的SSH服务支持OpenSSH格式的公钥认证,可以通过Linux、Mac OS X、或Cygwin下的ssh-keygen命令创建公钥/私钥对。命令如下:

$ ssh-keygen

然后根据提示在用户主目录下的.ssh目录中创建默认的公钥/私钥对文件,其中~/.ssh/id_rsa是私钥文件,~/.ssh/id_rsa.pub是公钥文件。注意私钥文件要严加保护,不能泄露给任何人。如果在执行ssh-keygen命令时选择了使用口令保护私钥,私钥文件是经过加密的。至于公钥文件~/.ssh/id_rsa.pub则可以放心地公开给他人。

也可以用ssh-keygen命令以不同的名称创建多个公钥,当拥有多个GitHub账号时,非常重要。这是因为虽然一个GitHub账号允许使用多个不同的SSH公钥,但反过来,一个SSH公钥只能对应于一个GitHub账号。下面的命令在~/.ssh目录下创建名为gotgithub的私钥和名为gotgithub.pub的公钥文件。

$ ssh-keygen -C "gotgithub@gmail.com" -f ~/.ssh/gotgithub

当生成的公钥/私钥对不在缺省位置(~/.ssh/id_rsa等)时,使用ssh命令连接远程主机时需要使用参数-i <filename>指定公钥/私钥对。或者在配置文件~/.ssh/config中针对相应主机进行设定。例如对于上例创建了非缺省公钥/私钥对~/.ssh/gotgithub,可以在~/.ssh/config配置文件中写入如下配置。

Host github.com
User git
Hostname github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/gotgithub

好了,有了上面的准备,就将~/.ssh/gotgithub.pub文件内容拷贝到剪切板。公钥是一行长长的字符串,若用编辑器打开公钥文件会折行显示,注意拷贝时切莫在其中插入多余的换行符、空格等,否则在公钥认证过程因为服务器端和客户端公钥不匹配而导致认证失败。命令行下可直接用pbcopy命令[2]将文件内容拷贝到剪切板以避免拷贝错误:

$ cat ~/.ssh/gotgithub.pub | pbcopy
然后将公钥文件中的内容粘贴到GitHub的SSH公钥管理的对话框中,如图2-8所示。


图2-8:添加SSH公钥认证

设置成功后,再用ssh命令访问GitHub,会显示一条认证成功信息并退出。在认证成功的信息中还会显示该公钥对应的用户名。

$ ssh -T git@github.com
Hi gotgithub! You've successfully authenticated, but GitHub does not provide shell access.

如果您未能看到类似的成功信息,可以通过在ssh命令后面添加-v参数加以诊断,会在冗长的会话中看到认证所使用的公钥文件等信息。然后比对所使用的公钥内容是否和GitHub账号中设置的相一致。

$ ssh -Tv git@github.com
...
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/jiangxin/.ssh/gotgithub
...
debug1: Entering interactive session.
Hi gotgithub! You've successfully authenticated, but GitHub does not provide shell access.
...

补充:
Mac下的命令行工具pbcopy和pbpaste可以在命令行下操作剪贴板,Linux下的命令行工具xsel亦可实现类似功能。在Linux下可以创建别名用xsel命令来模拟pbcopy和pbpaste 。

alias pbcopy='xsel --input'
alias pbpaste='xsel --output'

链接 https://help.github.com/articles/set-up-git
0 0