Last active
August 29, 2015 13:56
-
-
Save gnue/8928361 to your computer and use it in GitHub Desktop.
Dockerコンテナを指定して ssh 接続するスクリプト(SSH鍵の転送には ssh-copy-id が必要)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
docker run で
-p 22
を指定しなくても起動できるようにしたよ