我想使用多个私钥连接到不同的服务器或同一服务器的不同部分(我的用途是服务器的系统管理、Git管理和同一服务器中的正常Git使用)。我尝试简单地将密钥堆叠在id_rsa文件中,但没有用。
显然,要做到这一点,一个简单的方法是使用命令
ssh -i <key location> login@server.example.com
这很麻烦。
有什么建议可以让你做这件事更容易一些吗?
我想使用多个私钥连接到不同的服务器或同一服务器的不同部分(我的用途是服务器的系统管理、Git管理和同一服务器中的正常Git使用)。我尝试简单地将密钥堆叠在id_rsa文件中,但没有用。
显然,要做到这一点,一个简单的方法是使用命令
ssh -i <key location> login@server.example.com
这很麻烦。
有什么建议可以让你做这件事更容易一些吗?
当前回答
Generate an SSH key: $ ssh-keygen -t rsa -C <email1@example.com> Generate another SSH key: $ ssh-keygen -t rsa -f ~/.ssh/accountB -C <email2@example.com> Now, two public keys (id_rsa.pub, accountB.pub) should be exists in the ~/.ssh/ directory. $ ls -l ~/.ssh # see the files of '~/.ssh/' directory Create configuration file ~/.ssh/config with the following contents: $ nano ~/.ssh/config Host bitbucket.org User git Hostname bitbucket.org PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa Host bitbucket-accountB User git Hostname bitbucket.org PreferredAuthentications publickey IdentitiesOnly yes IdentityFile ~/.ssh/accountB Clone from default account. $ git clone git@bitbucket.org:username/project.git Clone from the accountB account. $ git clone git@bitbucket-accountB:username/project.git
注意:由于User git指令,你可以省略repo URL的git@部分,像这样缩短你的克隆命令:
$ git clone bitbucket-accountB:username/project.git
这是该指令的唯一目的。如果你不需要它(例如,你总是从网站复制粘贴git克隆命令),你可以把它从配置中去掉。
点击这里查看更多信息
其他回答
Randal Schwartz的回答几乎帮助了我。 我在服务器上有一个不同的用户名,所以我必须在我的文件中添加User关键字:
Host friendly-name
HostName long.and.cumbersome.server.name
IdentityFile ~/.ssh/private_ssh_file
User username-on-remote-machine
现在你可以使用friendly-name进行连接:
ssh friendly-name
更多关键字可以在OpenSSH手册页上找到。注意:列出的一些关键字可能已经出现在/etc/ssh/ssh_config文件中。
您可以在~/中创建一个名为config的配置文件。ssh文件夹。它可以包含:
Host aws
HostName *yourip*
User *youruser*
IdentityFile *idFile*
这将允许您像这样连接到机器
ssh aws
现在,使用最新版本的Git,我们可以在特定于存储库的Git配置文件中指定sshCommand:
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
sshCommand = ssh -i ~/.ssh/id_rsa_user
[remote "origin"]
url = git@bitbucket.org:user/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
前面的回答已经正确地解释了如何创建一个配置文件来管理多个ssh密钥。我认为,还需要解释的重要事情是在克隆存储库时用别名替换主机名。
假设,您公司的GitHub帐户的用户名是abc1234。 假设你的个人GitHub账户的用户名是jack1234
并且,假设您已经创建了两个RSA密钥,即id_rsa_company和id_rsa_personal。因此,您的配置文件将如下所示:
# Company account
Host company
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_company
# Personal account
Host personal
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_personal
现在,当你从公司的GitHub帐户克隆存储库(命名为demo)时,存储库URL将类似于:
Repo URL: git@github.com:abc1234/demo.git
现在,在做git克隆时,你应该把上面的存储库URL修改为:
git@company:abc1234/demo.git
注意github.com现在是如何被我们在配置文件中定义的别名“company”所取代的。
同样,您必须根据配置文件中提供的别名修改个人帐户中存储库的克隆URL。
ssh-add ~/.ssh/xxx_id_rsa
请确保在添加之前进行测试:
ssh -i ~/.ssh/xxx_id_rsa username@example.com
如果你有任何错误的问题,有时改变文件的安全性有助于:
chmod 0600 ~/.ssh/xxx_id_rsa