在 pod 中操作宿主机
要在 pod 中操作宿主机,有以下几种方式:
- 在 pod 中使用 ssh 连接到物理机,然后使用物理机的命令
- 物理机上有 agent,pod 调用 agent 执行命令
- 使用 特权 pod 操作宿主机
下面只介绍第三种方式。
apiVersion: v1
kind: Pod
metadata:
name: host-shell
spec:
containers:
- command:
- nsenter
- --target
- "1"
- --mount
- --uts
- --ipc
- --net
- --pid
- --
- bash
- -c
- cd ~ && exec bash -l
image: busybox:latest
name: host-shell
securityContext:
privileged: true
stdin: true
stdinOnce: true
tty: true
hostIPC: true
hostNetwork: true
hostPID: true
restartPolicy: Never
- hostIPC: true 让这个 Pod 共享宿主机的 IPC 命名空间,你可以看到和操作主机的信号量、消息队列、共享内存等。
- hostNetwork: true 让这个 Pod 共享宿主机的网络命名空间,你可以看到和操作主机的网络设备、IP 地址、路由表等。
- hostPID: true 让这个 Pod 共享宿主机的 PID 命名空间,你可以看到和操作主机的进程、线程、文件等。使用 nsenter 进入其他进程的 namespace
nsenter --target 1 --mount --uts --ipc --net --pid -- bash -c 'cd ~ && exec bash -l'
进入宿主机所有 namespace,然后执行一个交互式 bash 终端。
参数 | 含义 |
---|---|
nsenter | 工具,用于进入指定进程的命名空间 |
–target 1 | 进入 PID 为 1 的进程(即宿主机的 init 或 systemd) |
–mount | 指定要进入的命名空间类型(共享所有主机命名空间) |
– | 之后是你要执行的命令 |
bash -c | ‘cd ~ && exec bash -l’ 在主机命名空间中打开一个 Bash shell |
stdin: true
stdinOnce: true
tty: true
这些让 Pod 可以交互:
- stdin: true:接受标准输入
- tty: true:分配伪终端(必须有,才能像 SSH 那样交互)
- stdinOnce: true:连接断开后自动关闭