-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker-enter
executable file
·42 lines (35 loc) · 1.31 KB
/
docker-enter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/bin/sh
if [ -e $(dirname "$0")/nsenter ]; then
# with boot2docker, nsenter is not in the PATH but it is in the same folder
NSENTER=$(dirname "$0")/nsenter
else
NSENTER=nsenter
fi
if [ -z "$1" ]; then
echo "Usage: `basename "$0"` CONTAINER [COMMAND [ARG]...]"
echo ""
echo "Enters the Docker CONTAINER and executes the specified COMMAND."
echo "If COMMAND is not specified, runs an interactive shell in CONTAINER."
else
PID=$(docker inspect --format "{{.State.Pid}}" "$1")
[ -z "$PID" ] && exit 1
shift
COMMAND="$@"
if [ "$(id -u)" -ne "0" ]; then
which sudo > /dev/null
if [ "$?" -eq "0" ]; then
LAZY_SUDO="sudo "
else
echo "Warning: Cannot find sudo; Invoking nsenter as the user $USER." >&2
fi
fi
# Get environment variables from the container's root process
ENV=$($LAZY_SUDO cat /proc/$PID/environ | xargs -0)
# If no command is given, default to `su` which executes the default login shell
# Otherwise, execute the given command
[ -z "$COMMAND" ] && COMMAND="su -m root"
# Prepare nsenter flags
OPTS="--target $PID --mount --uts --ipc --net --pid --"
# Use env to clear all host environment variables and set then anew
$LAZY_SUDO "$NSENTER" $OPTS env -i - $ENV $COMMAND
fi