Skip to content

Instantly share code, notes, and snippets.

@mamemomonga
Last active July 1, 2019 08:12
Show Gist options
  • Select an option

  • Save mamemomonga/0786dafbee6e6ebf471b11b4bfcc7c2a to your computer and use it in GitHub Desktop.

Select an option

Save mamemomonga/0786dafbee6e6ebf471b11b4bfcc7c2a to your computer and use it in GitHub Desktop.
現在ログインしているUNIXユーザに、GitHubの任意ユーザがSSH接続できるようにする

現在ログインしているUNIXユーザに、GitHubの任意ユーザがSSH接続できるようにする

シェルスクリプトによる実行で、curl, jq が必要。

テスト用環境の準備

  • このサンプルでは、Dockerを使い、sshdの動作を確認する。
  • ローカルマシンからは 22000/TCP でsshdに接続することができる。

コマンド

[client]    $ docker run --rm -it -p 22000:22 ubuntu:bionic
[container] # apt update && apt install -y curl jq openssh-server

公開鍵の追加

  • 対象ユーザにログイン後、以下のスニペットを実行する。
  • このテストでは Dockerコンテナのrootでログインしているため、rootユーザに対して設定することになる。
  • TARGET_GITHUB_USERS="mamemomonga" を任意のGitHubユーザに書き換える。
  • TARGET_GITHUB_USERS="mamemomonga mogemamanga megemomongo" と言う風に複数書くことができる。
  • 公開鍵は追記される。余分なキーはvimなどで手作業で除去。

container で実行

bash << 'EOS'
TARGET_GITHUB_USERS="mamemomonga"
AKEY=$HOME/.ssh/authorized_keys
cd $HOME
mkdir -m 0700 -p $HOME/.ssh
if [ ! -e "$AKEY" ]; then
  touch $AKEY
  chmod 0600 $AKEY
fi
for i in $TARGET_GITHUB_USERS; do
  echo "[$i]"
  curl -s "https://api.github.com/users/$i/keys" | jq -r \
  '.[]|.key+" '$i'@github/"+(.id|tostring)' >> $AKEY
done
cat $AKEY
EOS

参照だけしたいとき

bash << 'EOS'
TARGET_GITHUB_USERS="mamemomonga"
for i in $TARGET_GITHUB_USERS; do
  echo "# $i"
  curl -s "https://api.github.com/users/$i/keys" | jq -r \
  '.[]|.key+" '$i'@github/"+(.id|tostring)'
done
EOS

接続の確認

sshdの起動

[container] $ /usr/sbin/sshd

-D オプションをつけるとdetachされない

クライアント側では先ほど追加したGitHubユーザの秘密鍵を事前にssh-add で読み込んでおく

[client] $ ssh -p 22000 root@localhost
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.9.125-linuxkit x86_64)
...

うまく接続できました

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment