[英]How to switch between SSH keys with the ruby-git gem?
有什么方法可以即時為ruby -git gem 配置設置不同的 SSH 密鑰,以便我可以使用不同的私有存儲庫?
我所做的工作很好,但它只適用於一個 SSH 密鑰。
我在 Rails 應用程序的根文件夾中創建了/ruby_git.sh
:
#!/bin/bash
exec /usr/bin/ssh -o StrictHostKeyChecking=no -i ./certs/private_key "$@"
我用我的 SSH 密鑰創建了/certs/private_key
:
-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----
我創建了/initializers/git_init.rb
:
Git.configure do |config|
config.git_ssh = Rails.root.join("ruby_git.sh").to_s
end
我還嘗試了另一種方法,在運行時為每個 repo 創建自定義 sh 腳本和 SSH 私鑰文件,並在使用后刪除它們。 但這似乎會全局更改Git
,因此下一個線程/會話繼承新的Git
配置:
# @repo_id, @ssh_url and @private_key are instance variables set
# based on the repo that we try to interact with
cert_path = Rails.root.join("git_config", "certs", @repo_id).to_s
config_path = Rails.root.join("git_config", "configs", "#{@repo_id}.sh").to_s
git_config = "#!\/bin\/bash\n\nexec \/usr\/bin\/ssh -o StrictHostKeyChecking=no -i #{cert_path} \"$@\""
File.open(config_path, "w") { |f|
f.write(git_config)
}
File.open(cert_path, "w") { |f|
f.write(@private_key)
}
File.chmod(0755, config_path)
File.chmod(0600, cert_path)
Git.init
Git.configure { |config|
config.git_ssh = config_path
}
Git.ls_remote(@ssh_url)
FileUtils.remove_entry(cert_path)
FileUtils.remove_entry(config_path)
您可以說,但是 ruby 設置為git -c core.sshcommand='/usr/bin/ssh -F my.temp.config'
並在該臨時配置中設置您的一次性連接設置參數。
您是否嘗試過放置 ssh 配置文件並指定要連接的主機?
我還沒有處理過 ruby 腳本。 我已經處理了足夠的 ssh 來處理此類事情。 有一個 ssh 配置文件可以幫助我解決這些用例。 它是~/.ssh/config
在您的用例中,您能否嘗試進行如下設置,
Host myfriendlyhostname1
HostName git.example.com
User user1
Port 1234
IdentityFile ~/.ssh/id_rsa1
Host myfriendlyhostname2
HostName git.example.com
User user2
Port 1234
IdentityFile ~/.ssh/id_rsa2
它的作用是,如果將上述內容放在~/.ssh/config
文件中,這將映射配置名稱以選擇連接
就您而言,我假設您具有相同的主機不同的憑據,對嗎?
如果您ssh myfriendlyhostname1
,它將使用為user1
提供的身份連接到git.example.com
。
如果您ssh myfriendlyhostname2
,它將使用為user2
提供的身份連接到git.example.com
。
搜索時,我發現這個鏈接有更多示例, https://linuxize.com/post/using-the-ssh-config-file/
我沒有嘗試過的是git clone
使用myfriendlyhostname1
如果您嘗試過,請告訴我情況如何。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.