1. 程式人生 > >使用nsenter工具進入Docker容器

使用nsenter工具進入Docker容器

Docker 虛擬化 nsenter

vi docker_enter.sh

#!/bin/sh

# 作 者: chengcheng

# 時 間: 2018-03-08

# 文 檔名: docker_enter.sh

# 版 本: 1.0.1

# 用 途: 使用nsenter工具進入Docker容器

# 用 法:. docker_enter 容器ID或bash -x docker_enter.sh 容器ID

# 正 文:如以下代碼

if [ -e $(dirname "$0")/nsenter ]; then

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")

if [ -z "$PID" ]; then

exit 1

fi

shift


OPTS="--target $PID --mount --uts --ipc --net --pid --"


if [ -z "$1" ]; then

# No command given.

# Use su to clear all host environment variables except for TERM,

# initialize the environment variables HOME, SHELL, USER, LOGNAME, PATH,

# and start a login shell.

"$NSENTER" $OPTS su - root

else

# Use env to clear all host environment variables.

"$NSENTER" $OPTS env --ignore-environment -- "$@"

fi

fi


使用nsenter工具進入Docker容器