├── .gitignore ├── LICENSE ├── README.md ├── example.py └── ubiquiti ├── __init__.py └── unifi.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | .idea/ 106 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 frehov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unifi-Python-API 2 | Conversion of the Unifi Shell API to python3 using Requests and Re 3 | 4 | #### Requirements: 5 | - Python 3.6 6 | - requests >= 2.18.4 7 | - typing >= 3.6.4 8 | 9 | ## Aim 10 | Deliver a "lightweight" easy to understand python api for the Unifi controller. 11 | The api is based off the following: 12 | 13 | 14 | 15 | ## Enhancements 16 | - Filter devices (regex) 17 | - Order devices by a key, defaults to '_id' 18 | 19 | ## Credits 20 | This Api is based on the work done by the following developers: 21 | 22 | - Unifi Shell API - https://dl.ubnt.com/unifi/5.7.23/unifi_sh_api 23 | - unifi-api by calmh - https://github.com/calmh/unifi-api 24 | - Unifi Api Browser by Art Of Wifi - https://github.com/Art-of-WiFi/UniFi-API-browser 25 | - Unifi Api Client by Art Of Wifi - https://github.com/Art-of-WiFi/UniFi-API-client 26 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from ubiquiti.unifi import API as Unifi_API 2 | import json 3 | 4 | 5 | # Example with context manager 6 | with Unifi_API(username="admin ", password="ubnt", baseurl="https://unifi:8443", verify_ssl=True) as api: 7 | device_list = (api.list_clients(filters={'hostname': 'Chromecast.*'}, order_by="ip")) 8 | print(json.dumps(device_list, indent=4)) 9 | 10 | 11 | # Example without contextmanager 12 | api = Unifi_API(username="ubnt", password="ubnt", baseurl="https://unifi:8443", verify_ssl=True) 13 | api.login() 14 | device_list = (api.list_clients(order_by="ip")) 15 | print(json.dumps(device_list, indent=4)) 16 | api.logout() -------------------------------------------------------------------------------- /ubiquiti/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frehov/Unifi-Python-API/d835c553749e4e19a398d0dc125c591ce9180394/ubiquiti/__init__.py -------------------------------------------------------------------------------- /ubiquiti/unifi.py: -------------------------------------------------------------------------------- 1 | from requests import Session 2 | import json 3 | import re 4 | from typing import Pattern, Dict, Union 5 | 6 | 7 | class LoggedInException(Exception): 8 | 9 | def __init__(self, *args, **kwargs): 10 | super(LoggedInException, self).__init__(*args, **kwargs) 11 | 12 | 13 | class API(object): 14 | """ 15 | Unifi API for the Unifi Controller. 16 | 17 | """ 18 | _login_data = {} 19 | _current_status_code = None 20 | 21 | def __init__(self, username: str="ubnt", password: str="ubnt", site: str="default", baseurl: str="https://unifi:8443", verify_ssl: bool=True): 22 | """ 23 | Initiates tha api with default settings if none other are set. 24 | 25 | :param username: username for the controller user 26 | :param password: password for the controller user 27 | :param site: which site to connect to (Not the name you've given the site, but the url-defined name) 28 | :param baseurl: where the controller is located 29 | :param verify_ssl: Check if certificate is valid or not, throws warning if set to False 30 | """ 31 | self._login_data['username'] = username 32 | self._login_data['password'] = password 33 | self._site = site 34 | self._verify_ssl = verify_ssl 35 | self._baseurl = baseurl 36 | self._session = Session() 37 | 38 | def __enter__(self): 39 | """ 40 | Contextmanager entry handle 41 | 42 | :return: isntance object of class 43 | """ 44 | self.login() 45 | return self 46 | 47 | def __exit__(self, *args): 48 | """ 49 | Contextmanager exit handle 50 | 51 | :return: None 52 | """ 53 | self.logout() 54 | 55 | def login(self): 56 | """ 57 | Log the user in 58 | 59 | :return: None 60 | """ 61 | self._current_status_code = self._session.post("{}/api/login".format(self._baseurl), data=json.dumps(self._login_data), verify=self._verify_ssl).status_code 62 | if self._current_status_code == 400: 63 | raise LoggedInException("Failed to log in to api with provided credentials") 64 | 65 | def logout(self): 66 | """ 67 | Log the user out 68 | 69 | :return: None 70 | """ 71 | self._session.get("{}/logout".format(self._baseurl)) 72 | self._session.close() 73 | 74 | def list_clients(self, filters: Dict[str, Union[str, Pattern]]=None, order_by: str=None) -> list: 75 | """ 76 | List all available clients from the api 77 | 78 | :param filters: dict with valid key, value pairs, string supplied is compiled to a regular expression 79 | :param order_by: order by a valid client key, defaults to '_id' if key is not found 80 | :return: A list of clients on the format of a dict 81 | """ 82 | 83 | r = self._session.get("{}/api/s/{}/stat/sta".format(self._baseurl, self._site, verify=self._verify_ssl), data="json={}") 84 | self._current_status_code = r.status_code 85 | 86 | if self._current_status_code == 401: 87 | raise LoggedInException("Invalid login, or login has expired") 88 | 89 | data = r.json()['data'] 90 | 91 | if filters: 92 | for term, value in filters.items(): 93 | value_re = value if isinstance(value, Pattern) else re.compile(value) 94 | 95 | data = [x for x in data if term in x.keys() and re.fullmatch(value_re, x[term])] 96 | 97 | if order_by: 98 | data = sorted(data, key=lambda x: x[order_by] if order_by in x.keys() else x['_id']) 99 | 100 | return data 101 | --------------------------------------------------------------------------------