我想使用多个私钥连接到不同的服务器或同一服务器的不同部分(我的用途是服务器的系统管理、Git管理和同一服务器中的正常Git使用)。我尝试简单地将密钥堆叠在id_rsa文件中,但没有用。
显然,要做到这一点,一个简单的方法是使用命令
ssh -i <key location> login@server.example.com
这很麻烦。
有什么建议可以让你做这件事更容易一些吗?
我想使用多个私钥连接到不同的服务器或同一服务器的不同部分(我的用途是服务器的系统管理、Git管理和同一服务器中的正常Git使用)。我尝试简单地将密钥堆叠在id_rsa文件中,但没有用。
显然,要做到这一点,一个简单的方法是使用命令
ssh -i <key location> login@server.example.com
这很麻烦。
有什么建议可以让你做这件事更容易一些吗?
当前回答
我喜欢在~/.ssh/config文件中设置以下方法:
# Configuration for GitHub to support multiple GitHub keys
Host github.com
HostName github.com
User git
# UseKeychain adds each keys passphrase to the keychain so you
# don't have to enter the passphrase each time.
UseKeychain yes
# AddKeysToAgent would add the key to the agent whenever it is
# used, which might lead to debugging confusion since then
# sometimes the one repository works and sometimes the
# other depending on which key is used first.
# AddKeysToAgent yes
# I only use my private id file so all private
# repositories don't need the environment variable
# `GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa"` to be set.
IdentityFile ~/.ssh/id_rsa
然后在你的存储库中创建一个.env文件,其中包含要使用的ssh命令:
GIT_SSH_COMMAND="ssh -i ~/.ssh/your_ssh_key"
如果你使用dotenv,环境变量会自动导出,你可以为每个项目/目录指定你想要的键。口令只被请求一次,因为它被添加到密钥链中。
这个解决方案与Git一起完美地工作,并且设计为在Mac上工作(由于UseKeychain)。
其他回答
这是我从sajib-khan的回答中得到的灵感。没有设置默认配置;这是我在GitLab上的个人账号,另一个是我的公司账号。以下是我所做的:
生成SSH密钥
ssh-keygen -t rsa -f ~/.ssh/company -C "name.surname@company.com"
编辑SSH配置
nano ~/.ssh/config
Host company.gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/company
删除缓存的SSH密钥
ssh-add -D
测试它!
ssh -T git@company.gitlab.com
欢迎来到GitLab, @hugo.sohm!
ssh -T git@gitlab.com
欢迎你的芳名…
使用它!
公司账户
git clone git@company.gitlab.com:group/project.git
个人/默认账户
git clone git@gitlab.com:username/project.git
这是我使用的源代码。
从我的.ssh/config:
Host myshortname realname.example.com
HostName realname.example.com
IdentityFile ~/.ssh/realname_rsa # private key for realname
User remoteusername
Host myother realname2.example.org
HostName realname2.example.org
IdentityFile ~/.ssh/realname2_rsa # different private key for realname2
User remoteusername
然后您可以使用以下连接:
ssh myshortname
SSH我的其他
等等。
对我来说,在MacOs上,唯一可行的解决方案就是在文件~/.ssh/config中添加这个:
Host *
IdentityFile ~/.ssh/your_ssh_key
IdentityFile ~/.ssh/your_ssh_key2
IdentityFile ~/.ssh/your_ssh_key3
AddKeysToAgent yes
Your_ssh_key没有任何扩展名。不要使用.pub。
在Ubuntu 18.04 (Bionic Beaver)上没有什么可做的。
成功创建第二个SSH密钥后,系统将尝试为每个连接查找匹配的SSH密钥。
你可以用下面这些命令创建一个新密钥:
# Generate key make sure you give it a new name (id_rsa_server2)
ssh-keygen
# Make sure ssh agent is running
eval `ssh-agent`
# Add the new key
ssh-add ~/.ssh/id_rsa_server2
# Get the public key to add it to a remote system for authentication
cat ~/.ssh/id_rsa_server2.pub
您可以尝试这个sshmulti npm包来维护多个SSH密钥。