How can I use the Python nftables library in a virtual environment?

Question:

Debian has a package called python3-nftables. You can install it with apt. It lets you interact with nftables (the modern iptables replacement).

Normally, when apt has a Python library, the library can also be found on pypi.org, which means the library can be included in a requirements.txt file, and be installed along with any other Python libraries when the virtual environment is being set up. Unfortunately, as far as I can tell, this package is not available on pypi.org.

If I install it with apt, and run python3, I can import nftables. Great.
The problem is that when you enter a virtual environment and try the same thing – import nftables, it won’t be found, because by default, the virtual environment ignores any system libraries installed with apt.

You can, of course, tell it to include those with --system-site-packages when creating the virtual environment, but there’s a reason this isn’t enabled by default.

After installing python3-nftables with apt, I can also copy the package (/usr/lib/python3/dist-packages/nftables) directly into my project folder, and include it in my project’s git repo. That works, but seems a bit hackey.

Is there a proper way to install the nftables library inside of the virtual environment, instead of installing it system-wide, and forcing the virtual environment to see it?

Asked By: John

||

Answers:

The source code is at https://salsa.debian.org/pkg-netfilter-team/pkg-nftables/-/tree/master/py. There is setup.py so you can do

pip install 'git+https://salsa.debian.org/pkg-netfilter-team/pkg-nftables#egg=nftables&subdirectory=py'
Answered By: phd

I have created a copy of the module and uploaded it to PyPI to use it in a project of mine.
https://github.com/ansibleguy/python3-nftables

pip install ansibleguy-nftables

You could install it or create a pypi account yourself and create your own package if you want to ‘control the source’.

Answered By: ansibleguy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.