Salim Fadhley Salim Fadhley -4 years ago 53
Linux Question

Can I get programmatic access to ulimit and sysctl.conf vars in Python?

I'd like to verify that a large number of Linux hosts are set up correctly. Currently I can do this by grepping sysctl.conf and executing commands like ulimit:

[username@hostname ~]$ tail -2 /etc/sysctl.conf
fs.file-max = 65536
vm.max_map_count = 262144
[username@hostname ~]$ ulimit -u

I'd like to write a script to gather all the following data:

  • Maximum file descriptors

  • Max threads

  • Max map count

Sure, I can get this by automating my manual process, but is there a more programmatic way of getting this data in Python? I'd rather know what the OS reports the value as, and not what's in the config file - just in case there's a difference.

Answer Source

There are two locations you can get this information:

  • for ulimit information, use the resource module; the process limit is the resource.RLIMIT_NPROC constant.

    import resource
    nproc_soft, nproc_hard = resource.getrlimit(resource.RLIMIT_NPROC)
  • For reading current sysctl.conf values, read the /proc/sys filesystem. The options in sysctl.conf map one-on-one to paths in that system, just replace . with a path separator:

    # read the current setting for fs.file-max
    with open('/proc/sys/fs/file-max') as f:
        file_max = int(
    # thread count limit, kernel.threads-max
    with open('/proc/sys/kernel/threads-max') as f:
        threads_max = int(
    # map count limit, vm.max_map_count
    with open('/proc/sys/vm/max_map_count') as f:
        max_map_count = int(
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download