Skip to content Skip to sidebar Skip to footer

Using Ufw (uncomplicatedfirewall) As An Api

I know that ufw is written in python. Is it possible to use ufw as an api via python?

Solution 1:

Sure, the ufw executable is just a thin wrapper around a python package with the same name. I'm not aware of any documentation, but you can just poke around the source and have a look how everything works. Find the ufw script location using which ufw and the package location by starting the python interpreter, importing the ufw module and asking it for its import path:

simon@mymachine:~$ python
Python 2.6.5 (r265:79063, Apr 162010, 13:57:41) 
[GCC 4.4.3] on linux2
Type"help", "copyright", "credits"or"license"for more information.
>>> import ufw
>>> ufw.__file__
'/usr/lib/python2.6/dist-packages/ufw/__init__.pyc'>>> 

Solution 2:

I created a wrapper, easyufw, to enable the use of ufw as an api.

Blog post here.

Repository here.

setup

You can pull easyufw from GitLab like this:

git clone https://gitlab.com/dhj/easyufw.git

You will also need ufw and you will need to run easyufw with root privileges because ufw requires it:

sudo pip install ufw
sudo python

try it

Once you are set up you can type these commands into a python terminal to get a feel for how easy it is.

Note the interface is live -- there is no dry run so it will actually run the commands you give it. Be careful.

import easyufw.easyufw as ufw

print ufw.status()
ufw.enable() # enable the firewall
ufw.deny('22/tcp') # disable ssh -- could disable active sessions!
ufw.allow('22/tcp') # enable ssh -- '22' alone or as int includes tcp and udp
ufw.delete(22) # delete all rules for port 22 -- int required
ufw.disable() # this will leave your firewall disabled! (default in ubuntu, but IMO, not smart)

You can also run any arbitrary command with ufw.run like ufw.run('allow from 207.46.232.182') (after import easyufw.easyufw as ufw)

That's it. Hope it is useful.

Post a Comment for "Using Ufw (uncomplicatedfirewall) As An Api"