nsenter 常用操作

nsenter 是一个可以用来进入到目标程序说在 namespace 中运行命令的工具,一般可以用于在容器外 debug 容器中运行的程序。简单记录一下 nsenter 的常用用法。

常用参数
最常用的参数组合是:

# 有的版本不一定有 -a 这个参数
nsenter -a -t <pid> <command>
nsenter -m -u -i -n -p -t <pid> <command>

参数的含义如下:

-a, --all enter all namespaces of the target process by the default /proc/[pid]/ns/* namespace paths.
-m, --mount[=] enter mount namespace
-u, --uts[=] enter UTS namespace (hostname etc)
-i, --ipc[=] enter System V IPC namespace
-n, --net[=] enter network namespace
-p, --pid[=] enter pid namespace
-t, --target target process to get namespaces from

结合 docker 使用用于在某个容器的 namespace 中运行指定程序的常用命令是:

PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)
nsenter -m -u -i -n -p -t $PID <command>

或者

$ ps -elf|grep sshd
$ nsenter --target <PID> --mount --uts --ipc --net --pid

例子:

$ docker run --rm --name test -d busybox  sleep 10000
8115009baccc53a2a5f6dfff642e0d8ab1dfb95dde473d14fb9a06ce4e89364c

$ docker ps |grep busybox
8115009baccc        busybox             "sleep 10000"            9 seconds ago       Up 8 seconds                            test

$ PID=$(docker inspect --format {{.State.Pid}} 8115009baccc)

$ nsenter -m -u -i -n -p -t $PID ps aux
PID   USER     TIME  COMMAND
    1 root      0:00 sleep 10000
    7 root      0:00 ps aux

$ nsenter -m -u -i -n -p -t $PID hostname
8115009baccc
QQ:1061767621 Q群:215481318
原文地址:https://www.cnblogs.com/gaohongyu/p/14776189.html