SELinux Python Bindings (Shim)
The `selinux` library for Python provides a shim for interacting with the system's SELinux module. It allows Python applications to query SELinux status, manage security contexts, and perform other SELinux-related operations. It primarily acts as a wrapper around the system's native `_selinux` module, which is typically provided by the `libselinux-python` package on Linux distributions. The current version is 0.3.0, with an active release cadence driven by contributions.
Warnings
- breaking Version 0.3.0 changed the minimum Python requirement to 3.9. Projects using Python 3.8 or older will encounter installation errors or runtime issues.
- gotcha This `selinux` package from PyPI is a shim/wrapper for the system-level `_selinux` module. It does NOT install SELinux functionality or the necessary underlying C libraries (`libselinux`) or their Python bindings (`libselinux-python`). If these are not already present and configured on your operating system, the module's functionality will be severely limited or unavailable.
- gotcha Many SELinux operations, especially those that modify policy or contexts, require elevated privileges (e.g., root) or specific SELinux capabilities. Running such functions without the necessary permissions will result in `PermissionError` or other runtime exceptions.
- gotcha While v0.2.0 introduced changes to 'Avoid errors on non-selinux platforms', some functions might still raise errors or return misleading values if SELinux is disabled or the system's `_selinux` module is not correctly loaded. Always check `selinux.is_selinux_enabled()` first.
Install
-
pip install selinux
Imports
- selinux
import selinux
Quickstart
import selinux
if selinux.is_selinux_enabled():
print(f"SELinux is enabled: {selinux.security_getenforce() == 1}")
print(f"Current SELinux mode: {'Enforcing' if selinux.security_getenforce() == 1 else 'Permissive'}")
print(f"SELinux policy version: {selinux.security_getpolicyvers()}")
else:
print("SELinux is not enabled on this system or the module is not fully functional.")