nsenter Linux切换命令空间

发布时间: 更新时间: 总字数:577 阅读时间:2m 作者: IP上海 分享 网址

nsenter 命令可以在指定 命名空间(namespace) 中运行程序,它由 util-linux 包提供。

使用场景

  • 比较最典型的用途是进入容器的网络命令空间,比如抓包。由于容器比较轻量级,没有基础的命令,比如ipsstcpingtcpdump 等,虽然可以在容器内安装,但难免不会带来增大容器的大小,新建后需要重复安装等问题。因此,通过 nsenter 进入 netns 后,可以使用宿主机的命令调试容器网络。

安装

apt install util-linux

Help

$ nsenter --help

Usage:
 nsenter [options] [<program> [<argument>...]]

Run a program with namespaces of other processes.

Options:
 -a, --all              enter all namespaces
 -t, --target <pid>     target process to get namespaces from
 -m, --mount[=<file>]   enter mount namespace
 -u, --uts[=<file>]     enter UTS namespace (hostname etc)
 -i, --ipc[=<file>]     enter System V IPC namespace
 -n, --net[=<file>]     enter network namespace
 -p, --pid[=<file>]     enter pid namespace
 -C, --cgroup[=<file>]  enter cgroup namespace
 -U, --user[=<file>]    enter user namespace
 -S, --setuid <uid>     set uid in entered namespace
 -G, --setgid <gid>     set gid in entered namespace
     --preserve-credentials do not touch uids or gids
 -r, --root[=<dir>]     set the root directory
 -w, --wd[=<dir>]       set the working directory
 -F, --no-fork          do not fork before exec'ing <program>
 -Z, --follow-context   set SELinux context according to --target PID

 -h, --help             display this help
 -V, --version          display version

For more details see nsenter(1).

示例

docker 使用的 namespace 参考:Docker 容器 Namespaces 技术

  • 获取名称为 nginx 容器的网络命名空间
# k8s 获取 containerID
kubectl get pod <pod-name> -o yaml | grep containerID

# 获取容器进程 pid,该示例 pid 为 15126
docker inspect -f {{.State.Pid}} <container-id>

# 进入网络命名空间,并查看 ip 信息
$ nsenter -n -t 15126
$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
26: eth0@if27: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

# 也可以使用如下命令
nsenter --net=/proc/15126/ns/net
  • 进入容器所有命名空间,此时和使用 docker exec -it 进入容器差不多
$ nsenter -a -t 15126
-bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)
root@63ab1b97f4ae:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@63ab1b97f4ae:/# ps -ef
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 Jan15 pts/0    00:00:00 bash
root          23       0  0 04:01 ?        00:00:00 -bash
root          30      23  0 04:02 ?        00:00:00 ps -ef
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数