多 SSH Key 實現同一臺服務器部署多 Git 倉庫

本文以如下需求爲背景,介紹詳細的作法: 需在同一臺服務器同時部署兩個不一樣的 Github 倉庫(對 Bitbucket 等 git 服務一樣適用) root 用戶可在遠程登陸 SSH 後附上預期的 SSH Key 進行 git 命令操做 nginx 用戶進程(如 php-fpm)可在進程內附上預期的 SSH Key 進行 git 命令操做php

1. 生成多個 SSH Key

以 root 身份登陸服務器,爲 root 用戶和 nginx 用戶分別生成 SSH Key。nginx

倉庫 1:git

$ ssh-keygen -b 2048 -t rsa -f "~/.ssh/id_rsa_github_myrepo1"
$ sudo -u nginx ssh-keygen -b 2048 -t rsa -C "nginx@localhost" -f "/var/lib/nginx/.ssh/id_rsa_github_myrepo1"

倉庫 2:github

$ ssh-keygen -b 2048 -t rsa -f "~/.ssh/id_rsa_github_myrepo2"
$ sudo -u nginx ssh-keygen -b 2048 -t rsa -C "nginx@localhost" -f "/var/lib/nginx/.ssh/id_rsa_github_myrepo2"

此處的 nginx 用戶的主目錄因操做系統不一樣而擁有不一樣的路徑,經測試 CentOS 系的操做系統可能值爲:shell

"/var/lib/nginx"
"/var/cache/nginx"
"/usr/share/nginx"

之其一,請讀者執行服務器

sudo -u nginx ssh-keygenssh

查看並以實際路徑爲準,替換本文中的對應命令的路徑。如:ide

[root@localhost]# sudo -u nginx ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/cache/nginx/.ssh/id_rsa):
此處的 nginx 用戶的主目錄爲 "/var/cache/nginx"。

2. 獲取 SSH Key 公鑰

將生成好的 SSH Key 的公鑰部分添加到兩個 Github 倉庫設置的 Deploy Keys(部署密鑰)中。php-fpm

倉庫 1:測試

$ cat "~/.ssh/id_rsa_github_myrepo1.pub"
$ cat "/var/lib/nginx/.ssh/id_rsa_github_myrepo1.pub"

倉庫 2:

$ cat "~/.ssh/id_rsa_github_myrepo2.pub"
$ cat "/var/lib/nginx/.ssh/id_rsa_github_myrepo2.pub"

3. 將不一樣的 SSH Key 與「主機名」對應起來

編輯用戶的 SSH 配置文件,並指定主機的詳細自定義配置。

root 用戶:

$ nano "~/.ssh/config"
Host github.com-myrepo1
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github_myrepo1

Host github.com-myrepo2
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github_myrepo2

nginx 用戶:

$ nano "/var/lib/nginx/.ssh/config"
Host github.com-myrepo1
    HostName github.com
    User git
    IdentityFile /var/lib/nginx/.ssh/id_rsa_github_myrepo1

Host github.com-myrepo2
    HostName github.com
    User git
    IdentityFile /var/lib/nginx/.ssh/id_rsa_github_myrepo2

4. 進行 git 命令操做

完成了上述步驟,讀者如今能夠在 root 或 nginx 用戶登陸或以其運行的進程中執行 git 命令,而且會自動附上指定的 SSH Key。例如:

$ git clone git@github.com-myrepo1:tommy/myrepo1.git "/var/www/myrepo1"
$ git clone git@github.com-myrepo2:tommy/myrepo2.git "/var/www/myrepo2"

PHP 運行於 nginx 用戶的 php-fpm 進程時:

<?
header( 'Content-type: text/text' );
exit( shell_exec( 'cd /var/www/myrepo1; git pull origin master 2>&1' ) );
exit( shell_exec( 'cd /var/www/myrepo2; git pull origin master 2>&1' ) );

額外補充

修改 git 倉庫地址

git remote set-url <name> <newurl>
git remote set-url origin git@github.com-myrepo1:tommy/myrepo1.git
git remote set-url origin git@github.com-myrepo2:tommy/myrepo2.git

修改know_hosts

刪掉,從新生成便可。

rm -f ~/.ssh/know_hosts
ssh -T git@github.com
Hi Anonymous! You've successfully authenticated, but Github.com does not provide shell access.

修改config權限

Bad owner or permissions
sudo chmod 600 ~/.ssh/config
相關文章
相關標籤/搜索