Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

linux

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
4096

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.

like image 328
Salim Fadhley Avatar asked Feb 26 '26 01:02

Salim Fadhley


1 Answers

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(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())
    
like image 160
Martijn Pieters Avatar answered Feb 28 '26 13:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!