Skip to content

Instantly share code, notes, and snippets.

@gnue
Last active August 29, 2015 13:56
Show Gist options
  • Save gnue/8928361 to your computer and use it in GitHub Desktop.
Save gnue/8928361 to your computer and use it in GitHub Desktop.
Dockerコンテナを指定して ssh 接続するスクリプト(SSH鍵の転送には ssh-copy-id が必要)
#!/bin/bash
die() {
echo "$1" 1>&2
exit 1
}
usage() {
die "Usage: $(basename $0) [-s] [-u USER] CONTAINER"
}
USER=root
while getopts "su:h" opts; do
case $opts in
s) shift; setup=yes;;
u) shift; USER=$OPTARG; shift;;
h) shift; usage;;
esac
done
[ -z "$DOCKER_SSH_PORT" ] && DOCKER_SSH_PORT=2022
[ -n "$DOCKER_SSH_KEY" ] && SSH_OPTS="-i $DOCKER_SSH_KEY"
if [[ -n "$DOCKER_HOST" && ! "$DOCKER_HOST" =~ ^unix: ]]; then
docker_host=${DOCKER_HOST#tcp://}
docker_host=${docker_host%:*}
[ -z "$docker_host" ] && docker_host=localhost
PROXY_HOST="$SSH_OPTS -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p $DOCKER_SSH_PORT docker@$docker_host"
fi
container=$1; shift
if [[ "$setup" == yes && -z "$container" && -n "$PROXY_HOST" ]]; then
echo "SSH key copy to Docker VM..."
ssh-copy-id $PROXY_HOST
exit
fi
[ -z "$container" ] && usage
docker_port=`docker port $container 22`
host=${docker_port%:*}
port=${docker_port#*:}
if [ -z "$host" ]; then
host=`docker inspect -format="{{ .NetworkSettings.IPAddress }}" $container`
port=22
fi
[[ -z "$host" || -z "$port" ]] && usage
TARGET_HOST="$SSH_OPTS -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p $port $USER@$host $@"
if [ "$setup" == yes ]; then
echo "SSH key copy to Docker container..."
if [ -n "$PROXY_HOST" ]; then
ssh-copy-id -o ProxyCommand="ssh -W %h:%p $PROXY_HOST" $TARGET_HOST
else
ssh-copy-id $TARGET_HOST
fi
exit
fi
if [ -n "$PROXY_HOST" ]; then
ssh -o ProxyCommand="ssh -W %h:%p $PROXY_HOST" $TARGET_HOST
else
ssh $TARGET_HOST
fi
@gnue
Copy link
Author

gnue commented Feb 11, 2014

docker2ssh

Dockerコンテナを指定して ssh 接続するスクリプト(SSH鍵の転送には ssh-copy-id が必要)

使い方

Dockerコンテナに ssh で接続

$ docker2ssh コンテナID
  • docker run に -p 22 オプションを付けて起動すること
  • コンテナID は docker ps で確認

Dockerfile のビルドと実行

$ git clone https://gist.github.com/8928369.git docker-sshd
$ cd docker-sshd
$ docker build -t <yourname>/sshd .

$ docker run -d -t <yourname>/sshd

SSH鍵の転送

ssh-copy-id のインストール(OS Xの場合)

$ brew install ssh-copy-id

Dockerホストに SSH鍵を転送

$ docker2ssh -s

Dockerコンテナに SSH鍵を転送

$ docker2ssh -s コンテナID

環境変数

.bash_profile

export DOCKER_HOST=localhost
export DOCKER_SSH_PORT=2022
export DOCKER_SSH_KEY=/Users/gnue/.ssh/id_rsa_boot2docker_vm
  • DOCKER_SSH_PORT DOCKER_SSH_KEY は省略可

@gnue
Copy link
Author

gnue commented Feb 13, 2014

docker run で -p 22 を指定しなくても起動できるようにしたよ

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