如何用python获取linux文件系统下的所有inode?

How to get all the inodes under the linux filesystem with python?

我正在尝试对 inode 进行一些计算(获取它们的大小等...) 我在网上查到的都是如何获取某个文件或目录的inode,但是我想一次调用获取所有的inode,然后一个一个的使用有什么想法吗?

谢谢

这个怎么样?

import os
inodes = os.popen("sudo ls -Rli / | awk '{ print  }'").read().split('\n')
inodes = [int(i) for i in inodes if i.isnumeric()]

对于我的主文件夹,这是一个 returns 索引节点编号列表:

[11666512, 10223622, 10234894, 10223641, 10223637, 10617011, 10254828, 10249545, 10223642, 10223643, 10487015, 10223640, 11929556, 10223639, 10223644, 10486989]

澄清一下,ls 命令采用三个标志参数,RliR 执行递归搜索以检查文件夹中的所有文件和所有以 / 开头的子文件夹,l 格式化输出给我们一个列表,i 给我们索引节点。我们将结果传递给 awk 以获取包含 inode 的第一列,然后对该数据进行一些简单的清理。

您可以使用 Python3 中的 scandir 函数枚举所有 inode。

import os
inodes = [ ]
for dirname,subdirs,filenames in os.walk('/') :
    inodes.extend ( [ k.inode() for k in os.scandir(dirname) ] )

os.walk returns 所有目录。
os.scandir returns 每个目录中的所有条目。 如果你想获得起始目录的索引节点,你必须使用 os.stat 来实现。