我可以在 Python 中以编程方式访问 ulimit 和 sysctl.conf 变量吗?

Sal*_*ley 3 python linux

我想验证大量 Linux 主机是否设置正确。目前我可以通过 grepping sysctl.conf 并执行 ulimit 等命令来做到这一点:

[username@hostname ~]$ tail -2 /etc/sysctl.conf
fs.file-max = 65536
vm.max_map_count = 262144
[username@hostname ~]$ ulimit -u
4096
Run Code Online (Sandbox Code Playgroud)

我想编写一个脚本来收集以下所有数据:

  • 最大文件描述符
  • 最大线程数
  • 最大地图数量

当然,我可以通过自动化手动过程来获取此数据,但是是否有更编程的方式在 Python 中获取此数据?我宁愿知道操作系统报告的值是什么,而不是配置文件中的内容 - 以防万一存在差异。

Mar*_*ers 5

您可以从两个位置获取此信息:

  • 有关ulimit信息,请使用该resource模块;过程极限是resource.RLIMIT_NPROC常数。

    import resource
    
    nproc_soft, nproc_hard = resource.getrlimit(resource.RLIMIT_NPROC)
    
    Run Code Online (Sandbox Code Playgroud)
  • 要读取当前sysctl.conf值,请读取/proc/sys文件系统。中的选项sysctl.conf一对一映射到该系统中的路径,只需替换.为路径分隔符:

    # read the current setting for fs.file-max
    with open('/proc/sys/fs/file-max') as f:
        file_max = int(f.read())
    
    # thread count limit, kernel.threads-max
    with open('/proc/sys/kernel/threads-max') as f:
        threads_max = int(f.read())
    
    # map count limit, vm.max_map_count
    with open('/proc/sys/vm/max_map_count') as f:
        max_map_count = int(f.read())
    
    Run Code Online (Sandbox Code Playgroud)