如何查看`/proc/1/ns/{ns}`中设备的设备号?

如何查看`/proc/1/ns/{ns}`中设备的设备号?

如何查看设备的设备号/proc/1/ns/{ns}

我已经阅读了 Go 库的代码(见下文),其中指出可以确定容器是否位于主机命名空间中:未命名空间的设备号/proc/1/ns/{ns}为 4,其他任何值都更高。

现在,在没有用户命名空间或 cgroup 的新 Debian 容器中,我运行以下命令:

root@54d74f795843:/# ls -la /proc/1/ns
total 0
dr-x--x--x 2 root root 0 Feb 29 17:18 .
dr-xr-xr-x 9 root root 0 Feb 29 17:18 ..
lrwxrwxrwx 1 root root 0 Feb 29 17:18 cgroup -> 'cgroup:[4026531835]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 ipc -> 'ipc:[4026532290]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 mnt -> 'mnt:[4026532288]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 net -> 'net:[4026532293]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 pid -> 'pid:[4026532291]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 user -> 'user:[4026531837]'
lrwxrwxrwx 1 root root 0 Feb 29 17:18 uts -> 'uts:[4026532289]'

这里的4026531837是什么'user:[4026531837]'意思?我不能是设备号,因为容器使用与主机相同的用户命名空间(我已经验证了这一点)。

如何列出文件的设备号/proc/1/ns/{ns}?该ls -la命令显示这些文件是符号链接,那么它们怎么会有设备号呢?

amicontained/vendor/github.com/jessfraz/bpfd/proc/proc.go/

// HasNamespace determines if a container is using a particular namespace or the
// host namespace.
// The device number of an unnamespaced /proc/1/ns/{ns} is 4 and anything else is
// higher.
// Only works from inside a container.
func HasNamespace(ns string) (bool, error) {
    file := fmt.Sprintf("/proc/1/ns/%s", ns)

    // Use Lstat to not follow the symlink.
    var info syscall.Stat_t
    if err := syscall.Lstat(file, &info); err != nil {
        return false, &os.PathError{Op: "lstat", Path: file, Err: err}
    }

    // Get the device number. If it is higher than 4 it is in a namespace.
    if info.Dev > 4 {
        return true, nil
    }

    return false, nil
}

答案1

“用户:[4026531837]”中的 4026531837 在这里意味着什么?

这些数字是文件系统实现的文件的索引节点号nsfs,可以打开这些setns(2)文件并将其与命名空间关联起来。

如何列出文件 /proc/1/ns/{ns} 的设备号?

根据 systemd 问题讨论(通过 /proc/1/sched 进行虚拟化检测不再适用于 Linux 4.14+ ):

在我可以测试的系统上(带有内核 4.15.1 的 Arch、带有内核 4.9.65 的 Debian Jessie 和带有内核 4.13.0 的 Ubuntu Artful),未命名空间的设备号/proc/1/ns/pid似乎总是 4,而在 PID 命名空间中,它是一个不同的、更高的数字,显然与(PID?)命名空间的数量有关。您可以使用以下命令尝试一下:

stat --format %d /proc/1/ns/pid
4
sudo unshare --pid --fork --mount-proc stat --format %d /proc/1/ns/pid
36

相关内容