Упрощаем работу с Check Point API с помощью Python SDK
Вся мощь взаимодействия с API раскрывается при совместном использовании с програмным кодом, когда появляются возможности динамически формировать API запросы и инструменты для анализа API ответов. Однако, малозаметным до сих пор остаётся Python Software Development Kit (далее — Python SDK) для Check Point Management API, а зря. Он ощутимо упрощает жизнь разработчикам и любителям автоматизации. Python приобрёл огромную популярность в последнее время и я решил устранить пробел и сделать обзор основных возмоностей Check Point API Python Development Kit. Данная статья служит отличным дополнением другой статьи на Хабре Check Point R80.10 API. Управление через CLI, скрипты и не только. Мы же рассмотрим как написать скрипты с использованием Python SDK и остановимся подробнее на новом функционале Management API в версии 1.6(поддерживается начиная с R80.40). Для понимания статьи понадобятся базовые знания по работе с API и Python.
Check Point активно развивает API и на данный момент на свет появились:
-
— работа с сервером управления через API(и возможность исполнять скрипты на шлюзах под управлением сервера управления) — работа со шлюзами безопасности — работа с песочницей в облаке Check Point — работа с Identity Awareness blade на шлюзах — работа с порталом управления SMB шлюзами (Подробнее про SMB шлюзы) — взаимодействие c IoT контроллерами — работа с CloudGuard Connect (решение SD-WAN security) — работа с Dome9

Установка модуля
Модуль cpapi устанавливается быстро и просто из официального репозитария Check Point на github с помощью pip. Подбробная инструкция по установке есть в README.md. Данный модуль адаптирован для работы с версиями Python 2.7 и 3.7. В данной статье примеры будут приведены с использованием Python 3.7. Однако, Python SDK можно запускать прямо с сервера управления Check Point (Smart Management), но на них поддерживается только версия Python 2.7, поэтому в последнем разделе будет приведён код для версии 2.7. Сразу после установки модуля рекомендую посмотреть на примеры в директориях examples_python2 и examples_python3.
Начало работы
Для того, чтобы у нас появилась возможность работать с компонентами модуля cpapi необходимо импортировать из модуля cpapi как минимум два необходимых класса:
APIClient и APIClientArgs
Класс APIClientArgs отвечает за параметры подключения к API серверу, а класс APIClient отвечает за взаимодействие с API.
Определяем параметры подключения
Чтобы определить различные параметры подключения к API, нужно создать экземпляр класса APIClientArgs. В принципе его параметры предопределены и при запуске скрипта на сервере управления их можно не указывать.
Но при запуске на стороннем хосте нужно указать как минимум IP адрес или имя хоста API сервера(он же сервер управления). В примере ниже мы определяем параметр подключения server и присваиваем ему в виде строки IP адрес сервера управления.
Давайте посмотрим на все параметры и их значения по умолчанию, которые можно использовать при подключении к API серверу:
Полагаю, что аргументы, которые можно использовать в экземплярах класса APIClientArgs, интуитивно понятны администраторам Check Point и в дополнительных комментариях не нуждаются.
Подключаемся через APIClient и менеджер контекста
Класс APIClient удобнее всего использовать через менеджер контекста. Всё, что нужно передать экземпляру класса APIClient это параметры подключения, которые были определены в прошлом шаге.
Менеджер контекста не станет выполнять автоматически login вызов на API сервер, однако он выполнит вызов logout при выходе из него. Если по каким-то причинам logout по окончанию работы с API вызовами не требуется, нужно начать работу без использования менеджера контекста:
Проверка соединения
Проверить проходит ли соединение по заданным параметрам проще всего с помощью метода check_fingerprint. Если проверка хеш-суммы sha1 для fingerprint сертификата API сервера не прошла(метод вернул False), то обычно это вызвано проблемами с соединением и мы можем остановить выполнение программы(или дать пользователю возможность исправить данные для подключения):
Учтите, что в дальнейшем класс APIClient будет проверять при каждом API вызове (методы api_call и api_query, о них речь пойдёт чуть дальше) sha1 fingerprint сертификата на API сервере. А вот если при проверке sha1 fingerprint сертификата API сервера будет выявлена ошибка (сертификат неизвестен или был изменён), метод check_fingerprint предоставит возможность добавить/изменить информацию о нём на локальной машине в автоматическом режиме. Данную проверку можно отключить вовсе (но такое можно рекомендовать только в случае запуска скриптов на самом API сервере, при подключении к 127.0.0.1), используя аргумент APIClientArgs — unsafe_auto_accept (см. подробнее про APIClientArgs ранее в «Определяем параметры подключения»).
Login на API сервер
У APIClient есть целых 3 метода логина на API сервер, и каждый из них запонимает значение sid(session-id), которое использует автоматически в каждом последующем API вызове в заголовке(имя в заголовке у данного параметра — X-chkp-sid), так что не нужно дополнительно обрабатывать данный параметр.
Метод login
Вариант с использованием логина и пароля(в примере имя пользователя admin и пароль 1q2w3e переданы как позиционные аргументы):
В методе login доступны также дополнительные опциональные параметры, привожу их имена и значения по умолчанию:
Метод login_with_api_key
Вариант с использованием api ключа(поддерживается начиная с версии менеджмента R80.40/Management API v1.6, «3TsbPJ8ZKjaJGvFyoFqHFA==» это значение ключа API для одного из пользователей на сервере управления с методом авторизации API key):
В методе login_with_api_key доступны такие же опциональные параметры как и в методе login.
Метод login_as_root
Вариант login’а на локальную машину с API сервером:
Для данного метода доступны всего два опциональных параметра:
И наконец сами API вызовы
У нас есть два варианта делать API вызовы через методы api_call и api_query. Давайте разберёмся в чём между ними разница.
api_call
Данный метод применим для любых вызовов. Нам нужно передать последнюю часть для api вызова и payload в теле запроса при необходимости. Если payload пустой, то его можно не передавать вовсе:
api_query
Сразу оговорюсь, что данный метод применим только для вызовов, вывод которых предполагает offset(сдвиг). Такой вывод происходит в том случае, когда в нём содержится или может содержатся большое количество информации. Например, это может быть запрос списка всех созданных объектов типа хост на сервере управления. Для таких запросов API возвращает список из 50 объектов по умолчанию(можно увеличить лимит до 500 объектов в ответе). И для того, чтобы не дёргать информацию по несколько раз, меняя параметр offset в API запросе, есть метод api_query, который данную работу проделывает автоматически. Примеры вызовов, где нужен данный метод: show-sessions, show-hosts, show-networks, show-wildcards, show-groups, show-address-ranges, show-simple-gateways, show-simple-clusters, show-access-roles, show-trusted-clients, show-packages. По факту, в имени этих API вызовов мы видим слова во множественном числе, так что эти вызовы будет проще обрабатывать через api_query
Обработка результатов API вызовов
После этого можно использовать переменные и методы класса APIResponse(как внутри менеджера контекста, так и снаружи). У класса APIResponse предопределено 4 метода и 5 переменных, на самых важных мы остановимся подробнее.

success
Для начала было бы неплохо убедиться в том, что API вызов прошёл успешно и вернул результат. Для этого есть метод success:
Возвращает True если API вызов прошёл успешно(Код ответа — 200) и False если не успешно(любой другой код ответа). Удобно использовать сразу после API вызова, чтобы в зависимости от кода ответа вывести разную информацию.
statuscode
Возвращает код ответа после выполнения API вызова.
Возможные коды ответов: 200,400,401,403,404,409,500,501.
set_success_status
При этом может быть необходимость изменить значение статуса success. Технически, туда можно поместить что угодно, даже обычную строку. Но реальным примером может быть сброс данного параметра в False при определенных сопутствующих условиях. Ниже обратите внимание на пример, когда есть задачи, выполняемые на сервере управления, но мы будем считать этот запрос неудачным(выставим переменную success в False, несмотря на то, что API вызов был успешный и вернул код 200).
response()
Метод response позволяет посмотреть словарь с кодом ответа(status_code) и с телом ответа(body).
Позволяет увидеть только тело ответа(body) без излишней информации.
error_message
Данная информация доступна, только когда при обработке API запроса возникла ошибка(код ответа не 200). Пример вывода
Полезные примеры
Ниже перечислены примеры, в которых используются API вызовы, которые были добавлены в версию Management API 1.6.
Для начала рассмотрим работу вызовов add-host и add-address-range. Допустим, нам нужно создать в качестве объектов типа хост все ip адреса подсети 192.168.0.0/24, последний октет которых равен 5, а все остальные ip адреса записать в качестве объектов типа диапазон адресов. При этом, адрес подсети и широковещательный адрес исключить.
Итак, ниже представлен скрипт в котором решается данная задача и создаются 50 объектов типа хост и 51 объект типа диапазон адресов. На решение задачи требуется 101 API вызов(не считая финального вызова publish). Также с помощью модуля timeit мы подсчитываем время на выполнение скрипта до момента публикации изменений.
В моей лабораторной среде на выполнение данного скрипта уходит от 30 до 50 секунд в зависимости от нагрузки на сервер управления.
А теперь посмотрим как решить эту же задачу с помощью API вызова add-objects-batch, поддержка которого добавлена в версию API 1.6. Данный вызов позволяет за один API запрос создать сразу множество объектов. Причём это могут быть объекты разных типов(например хосты, подсети и диапазоны адресов). Таким образом наша задача может быть решена в рамказ одного API вызова.
А на выполнение данного скрипта в моей лабораторной среде уходит от 3 до 7 секунд в зависимости от нагрузки на сервер управления. То есть, в среднем, на 101 объекте API вызов типа batch, отрабатывает в 10 раз быстрее. На большем количестве объектов разница будет ещё более впечатляющей.
Теперь давайте посмотрим как работать с set-objects-batch. С помощью данного API вызова мы можем массово изменить любой параметр. Давайте настроим первой половине адресов из прошлого примера (до .124 хоста, причём и диапазонам тоже) цвет sienna, а второй половине адресов назначим цвет khaki.
Удалить множество объектов в одном API вызове можно с помощью delete-objects-batch. А теперь посмотрим на пример кода, который удаляет все хосты, созданные ранее через add-objects-batch.
Все функции, которые появляются в новых релизах ПО Check Point, сразу же обретают и API вызовы. Так, в R80.40 появились такие «фичи» как Revert to revision и Smart Task, и для них сразу же подготовили соответствующие API вызовы. Более того, весь функционал при переходе из Legacy консолей в режим Unified Policy также обрастает поддержкой API. Например, долгожданным обновлением в версии ПО R80.40 стал переезд политики HTTPS Inspection из Legacy режима в режим Unified Policy, и данный функционал сразу же получил API вызовы. Вот пример кода, который добавляет на верхнюю позицию HTTPS Inspection policy правило, которое исключает из инспекции 3 категории(Здоровье, Финансы, Государственные услуги), которые запрещено инспектировать в соответствии с законадательством в ряде стран.
Запуск Python скриптов на сервере управления Check Point
Всё в том же README.md содержится информация как запускать скрипты на Python прямо с сервера управления. Это может быть удобно, когда у вас нет возможности подключиться к API серверу с другой машины. Я записал шестиминутное видео в котором рассматриваю установку модуля cpapi и особенности запуска Python скриптов на сервере управления. В качестве примера запускается скрипт, который автоматизирует конфигурацию нового шлюза для такой задачи, как аудит сети Security CheckUp. Из особенностей, с которыми пришлось столкнуться: в версии Python 2.7 ещё не появилась функция input, поэтому для обработки информации, которую вводит пользователь, используется функция raw_input. В остальном, код такой же как для запуска с других машин, только удобнее использовать функцию login_as_root, дабы не указывать свои же собственные username, пароль и IP адрес сервера управления ещё раз.
Заключение
Данная статья рассматривает лишь основные возможности работы Python SDK и модуля cpapi(как вы могли догадаться, это фактически синонимы), и изучив код в данном модуле вы откроете для себя ещё больше возможностей в работе с ним. Не исключено, что у вас появится желание дополнить его своими классами, функциями, методами и переменными. Вы всегда можете делится своими наработками и просматривать другие скрипты для Check Point в разделе CodeHub в сообществе CheckMates, которое объединяет в себе и разработчиков продуктов и пользователей.
How to build a user-friendly Python SDK
No matter how well designed and implemented an application may be, if the user experience sucks, the application won’t be effective. Dashboard and monitoring products in particular are often marketed and designed for different end users: analysts, business leaders, software engineers. Each user may have a different preferred interface to use the application. Analysts may often use a GUI while a data scientist may use an API or SDK. The challenge is often designing the best user experience across all of these different user interfaces.
At Arthur we’ve taken an API-first approach when designing and building our model monitoring platform. The API exposes functionality to allow customers to manage their machine learning models, send inferences as they are computed, and retrieve information related to the performance of their model. Most data scientists prefer to interact with our platform through our Python SDK, which eventually communicates with our REST API. Our SDK seamlessly integrates with model pipelines, which often are in the form of Jupyter Notebooks. As we’ve built out this functionality we’ve learned a lot about best practices and techniques for creating an SDK. Here’s what we’ve done to build a user-friendly SDK:
Create Clear Function and Class Import Paths
Pathing became a large focus as we were designing our SDK. We want to ensure that users can anticipate the location of utility functions, core SDK classes, and constants they may need to use throughout development. Logical pathing also can be helpful when using autocomplete in IDEs. We determined four main packages that all modules will live under.
- Client, handles HTTP communication with our REST API
- Common, contains constants and exceptions that may be referenced or used in other pieces of the SDK
- Core, contains all core classes that are used to interact with our application ( ArthurModel and ArthurAttribute )
- Explainability, contains model explainability specific code
While organizing code logically can make it easier for users to find import paths, we generally will create shortcuts for commonly used objects. The easiest way to do this is to import a module in a root package __init__.py file. For example, since the ArthurModel is located in arthurai.core.model.ArthurModel we created a shortcut by importing it directly to the arthurai package. This simplifies the syntax to from arthurai import ArthurModel . Logically organizing our code not only makes it easier for users to interface with the SDK, but also helps organize the documentation intuitively.
Provide Thorough Documentation
Code documentation is a vital part in ensuring we create an easy to use SDK. We use RestructuredText and Sphinx to auto-generate user documentation. ReStructuredText is a plaintext markup syntax which can be used in Python function and class inline documentation. Sphinx is a framework which can auto-generate documentation from reStructuredText and export it to multiple formats including HTML. Sphinx is often used to generate Python library documentation and while reStructuredText is the recommended markup syntax for Python documentation (PEP 287), there are three markup syntax options that most developers will use:
ReStructuredText
Google-style
Numpy-style
There are pros and cons to each style and a decision on which to use in your library often comes down to personal preference. We chose to use reSructuredText because of its easy integration with Sphinx and some of our developers familiarity with it. As I mentioned Sphinx supports reStructuredText out of the box, but a plugin called Napoleon can be used to add Google and NumPy style support.
Set Clear Function Design Conventions
While most of the basic functionality of our application is integrated into our SDK, to ensure nimble and clean future development we outline 8 guidelines which our engineers use when creating new functionality.
- Determine what package/module new code/functions should live under, or in rare cases, whether a new package or module should be created.
- Do not use static methods ( @staticmethod ) for client facing functions; instead, use module level functions. If a function is not associated with an instance of a class, and is a utility function, it is more clear to associate the function with a module.
- Do not use simple getter and setter functions. Use Python @property tags instead. In addition to being more pythonic, this maintains a syntax similar to directly accessing attributes but allows more control over how the attributes are retrieved and manipulated.
- A function’s action should be represented by its name.
- Try to not hide function operations from clients. For example, if a function significantly transforms its input before storing or sending it to the API then consider creating and exposing a helper function for the client to use. Ensure documentation and error handling is properly updated to guide clients to use this helper function.
- Create functions which do specific operations rather than generic functions with optional parameters. If clients use incorrect function, exceptions should direct them toward the correct function for their use-case.
- Specify function parameters and generally avoid *kwargs .
- Functions which do similar operation should have similar names. In addition, similar parameters should be in the same order with unique parameters appended at the end.
Give Clear Explanation of Exceptions and Error Handling
Many SDK functions will interact with backend microservices or utilize code from 3rd party libraries, any of which could throw an exception. This increases the importance of error handling to ensure users can understand issues and guide themselves to a solution.
Within our SDK, we use custom exceptions to handle errors that occur. Inspired by Python’s hierarchical organization of exceptions (Python Exception Hierarchy), we have taken a similar approach to ensure development is smooth and error messages are clear. At the top of the tree is a Base Exception class which contains helper functions and standardizes our error message format.
Most function calls within our SDK contain a HTTP call to our REST API. API calls generally return errors through HTTP response codes. However, to add extra functionality and convenience in our SDK, we may add additional error handling to our REST calls. To do this we handle all HTTP responses within the SDK functions and not within our HTTP Client package. This allows us to customize API response handling within the context of each SDK function. For example, when calling ArthurModel.save() we hit a POST endpoint on our API by calling the SDK HTTP client package ( client.post() ). Instead of handling any model save errors within the client.post() method we will pass them through to the ArthurModel._save_model_post() function which initiates the call.
Exceptions handled in HTTP Client:
Exceptions handled in SDK functions, allows for more module error handling:
Our SDK utilizes a handful of third party libraries which may throw their own exceptions. Another principle we take when using 3rd party packages is to catch exceptions and wrap those errors in our own messaging. This is done to help avoid confusion and give more context to unintended errors.
Testing Everything. Twice.
Testing a customer facing tool is vital. Our test suite primarily consists of unit tests which ensure the functionality of each function call within the SDK. SDK’s in general are often used by clients in various configured environments. For Python SDK’s this means different versions of Python and of existing libraries. Another aspect of an evolving application is ensuring backwards compatibility. Building and maintaining an expansive test suite can help ensure the library will work as intended in all of these situations.
Separate the Test Package
To simplify the structure and minimize the size of our SDK, we’ve separated the testing package from our SDK bundle. Since our testing package is separate, it is organized in the same manner as our SDK package. For example in our SDK the ArthurModel class is located at arthurai.core.models therefore the tests for ArthurModel are located in tests.core.models .
Mock HTTP Client Functions
Within the ArthurAI library we built our own custom wrapper to Python’s request library. The main advantage to this structure is so we can abstract all REST specific functionality to its own package within our library. While it is possible to mock the request library (we’ve used request-mock in the past) the structure we use also makes it easy to mock functions which make HTTP calls instead of dealing with the requests library directly.
Testing CI/CD
Before every PR is merged into our master branch we run a set of tests to ensure that each commit does not introduce new bugs into our library. For our testing suite we use Pytest. However in order to confirm that our library continues to be compatible with all supported Python versions we run our tests using a tool called Tox. Tox provides the ability to run the SDK test suite within different environments making it easy to test the code across different dependencies and versions of Python. In addition to running our test suite, we also run a linter to enforce code styling, conventions, and typing. We use a tool called MyPy for this.
Conclusion
Throughout iterating on the design and implementation of our SDK we found it’s easy to create a library to interface with an API, but it’s difficult to determine how to do this in a scalable and intuitive way which prioritizes the needs of both the developer and end user. The guidelines discussed above have helped us maintain a clean repository of code, made it easy for our developers to add functionality, and created a seamless environment to test and document the ArthurAI Python SDK.
Configure a Python SDK
The following is only valid when the Python plugin is installed and enabled.
To develop Python scripts in IntelliJ IDEA, download and install Python and configure at least one Python SDK. A Python SDK can be specified as a Python interpreter for Python project.
IntelliJ IDEA supports:
To view the list of available SDKs, choose File | Project Structure from the main menu Ctrl+Alt+Shift+S . Python SDKs can be configured on the following levels:



To easily tell them from each other, enter different names in the Name field. See SDKs for more information about SDK configuration.
To add a Python SDK, you must configure a Python interpreter. Regardless of the level, you can configure a local or a remote Python interpreter.
Configuring local Python interpreters
To configure a local Python interpreter, adhere to one of the following procedures:
Configure a system interpreter
Ensure that you have downloaded and installed Python on your computer.
Installing Python on Windows from Microsoft Store

If you are on Windows, you can download Python from the Microsoft Store and install it as a Python interpreter. Once the Python application is downloaded from the Microsoft Store, it becomes available in the list of the Python executables. Note that interpreters added from the Microsoft Store installations come with some limitations. Because of restrictions on Microsoft Store apps, Python scripts may not have full write access to shared locations such as TEMP and the registry.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select System Interpreter .
In the Interpreter field, type the fully-qualified path to the required interpreter executable, or click and in the Select Java Interpreter dialog that opens, choose the desired Java executable.


You will need admin privileges to install, remove, and upgrade packages for the system interpreter. When attempting to install an interpreter package through an intention action, you might receive the following error message: As prompted, consider using a virtual environment for your project.
Click OK to complete the task.
Create a virtualenv environment
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select Virtualenv Environment .
The following actions depend on whether you want to create a new virtual environment or to use an existing one.

Specify the location of the new virtual environment in the Location field, or click and browse for the desired location in your file system. The directory for the new virtual environment should be empty.

Choose the base interpreter from the list, or click and find the desired Python executable in your file system.
Select the Inherit global site-packages checkbox if you want all packages installed in the global Python on your machine to be added to the virtual environment you’re going to create. This checkbox corresponds to the —system-site-packages option of the virtualenv tool.
Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in IntelliJ IDEA.
Choose the desired interpreter from the list.
If the desired interpreter is not on the list, click , and then browse for the desired Python executable (for example, venv/bin/python on macOS or venv\Scripts\python.exe on Windows).
The selected virtual environment will be reused for the current project.
Click OK to complete the task.
If IntelliJ IDEA displays the Invalid environment warning, it means that the specified Python binary cannot be found in the file system, or the Python version is not supported. Check the Python path and install a new version, if needed.
Create a conda environment
Ensure that Anaconda or Miniconda is downloaded and installed on your computer, and you’re aware of a path to its executable file.
Refer to the installation instructions for more details.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select Conda Environment .
The following actions depend on whether you want to create a new conda environment or to use an existing one.

Specify the location of the new conda environment in the Location field, or click and browse for the desired location in your file system. The directory for the new conda environment should be empty.
Select the Python version from the list.
Normally, IntelliJ IDEA will detect conda installation.

Otherwise, specify the location of the conda executable, or click to browse for it.
Specify the environment name.
Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in IntelliJ IDEA.
Choose the desired environment from the list.
If the desired interpreter is not on the list, click, and then browse for the Python executable within the previously configured conda environment.
If necessary, specify the location of the conda executable, or click to browse for it.
Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in IntelliJ IDEA.
The selected conda environment will be reused for the current project.
Click OK to complete the task.
Create a pipenv environment
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select Pipenv Environment .

Choose the base interpreter from the list, or click and find the desired Python executable in your file system.
If you have added the base binary directory to your PATH environmental variable, you don’t need to set any additional options: the path to the pipenv executable will be autodetected.
If the pipenv executable is not found, follow the pipenv installation procedure to discover the executable path, and then paste it in the Pipenv executable field.
Click OK to complete the task.
Once all the steps are done, the new pipenv environment is set for your project and the packages listed in the Pipfile are installed.
If you open a project with a Pipfile file added but no any interpreter configured, IntelliJ IDEA offers you to use Pipenv environment.
![]()
If you select this option, IntelliJ IDEA sets pipenv for you automatically. Alternatively, you can click Configure Python interpreter to follow the standard workflow.
Similarly, when you open a project with a Pipfile file in IntelliJ IDEA for the very first time, for example, by checking it out from the Version Control, the Pipenv virtual environment will be configured automatically.
When you have set the Pipenv virtual environment as a Python interpreter, all available packages are added from the source defined in Pipfile . The packages are installed, removed, and updated in the list of the packages through pipenv rather than through pip.
Create a Poetry environment
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select Poetry Environment .
The following actions depend on whether you want to create a new Poetry environment or to use an existing one.
Select Poetry Environment .

Choose the base interpreter from the list, or click and find the desired Python executable in your file system.
If IntelliJ IDEA doesn’t detect the poetry executable, specify the following path in the Poetry executable field, replacing jetbrains with your username:
Make sure that the project directory contains a pyproject.toml file.
Select Existing environment . Then expand the Interpreter list and choose the desired interpreter.
If the desired interpreter is not on the list, click, and then browse for the Python executable within the previously configured Poetry environment.
The selected Poetry environment will be reused for the current project.
Click OK to complete the task.
Configuring remote Python interpreters
To configure a remote Python interpreter:
Configure a WSL interpreter
Click the Windows button in the lower-left corner of the screen and start typing System Information . To ensure that your system works well with WSL, upgrade your Windows to the latest available version.
Install the Windows Subsystem for Linux and initialize your Linux distribution as described in the WSL Installation Guide.
If your Linux distribution doesn’t come with rsync, you need to install it:
sudo apt install rsync
sudo pacman -S rsync
When working with WSL 2, mind the following known WSL issues:
Debugger doesn’t work properly if firewall is not opened for WSL IP.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select WSL .
Select the Linux distribution with the required Python interpreter.
In Python interpreter path field, specify the path to the Python executable. You can accept the default, type in a different path, or click to browse.
The configured remote interpreter is added to the list.
Configure an interpreter using Vagrant
Ensure that the following prerequisites are met (outside of IntelliJ IDEA):
One of supported Vagrant providers is installed on your computer.
Vagrant is installed on your computer, and all the necessary infrastructure is created.
The parent folders of the following executable files have been added to the system PATH variable:
vagrant.bat or vagrant from your Vagrant installation. This should be done automatically by the installer.
VBoxManage.exe or VBoxManage from your Oracle’s VirtualBox installation.
The required virtual boxes are created.
Make sure that the Vagrant plugin is installed and enabled.
Ensure that you have properly initiated and started Vagrant. Basically, you need to open the Terminal window and execute the following commands:
See Vagrant documentation for more information.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select Vagrant .
In Python interpreter path field, specify the path to the Python executable. You can accept the default, type in a different path, or click to browse.
The configured remote interpreter is added to the list.
Configure an interpreter using SSH
You cannot use a Windows machine as a remote host when configuring SSH interpreters.
Ensure that there is an SSH server running on a remote host, since IntelliJ IDEA runs remote interpreters via ssh-sessions.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
Select New server configuration , then specify server information (host, port, and username).

Alternatively, you can select Existing server configuration and choose any available deployment configuration from the list.

If needed, click to review the Connection settings, Mappings, and Excluded paths for the selected deployment configuration. Click Next to continue configuring an interpreter.

In the next dialog window, provide the authentication details to connect to the target server.
Select Password or Key pair (OpenSSH or PuTTY) and enter your password or passphrase. If Key pair (OpenSSH or PuTTY) is selected, specify:
Private key : location of the file with a private key
Passphrase : similar to a password, it serves to encrypt the private key.
Click Next to proceed.
In the next dialog window, verify the path to the desired Python interpreter. You can accept the default, or specify a different one. You have to configure the path mappings between your local project and the server. To do that, click next to the Sync folders field and enter the path to the local project folder and the path to the folder on the remote server.

You can also select the checkbox to enable automatic upload of the local changes to the remote server.
The configured remote interpreter is added to the list.
Configure an interpreter using Docker
Make sure that the following prerequisites are met:
Docker is installed, as described in the Docker documentation.
You have stable Internet connection, so that IntelliJ IDEA can download and run busybox:latest (the latest version of the BusyBox Docker Official Image). Once you have successfully configured an interpreter using Docker, you can go offline.
Note that you cannot install any Python packages into Docker-based project interpreters.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select Docker .
Select an existing Docker configuration in the Server dropdown.
Alternatively, click New and perform the following steps to create a new Docker configuration:
Create a Docker configuration
Click New to add a Docker configuration and specify how to connect to the Docker daemon.
The connection settings depend on your Docker version and operating system. For more information, see Docker connection settings.
The Connection successful message should appear at the bottom of the dialog.

The Path mappings table is used to map local folders to corresponding directories in the Docker virtual machine’s file system. Only specified folders will be available for volume binding.
This table is not available on Linux, because when running Docker on Linux, any folder is available for volume binding.
Specify the image and the path to the Python executable:
The configured remote interpreter is added to the list.
Configure an interpreter using Docker Compose
Make sure that the following prerequisites are met:
Docker is installed, as described in the Docker documentation.
You have stable Internet connection, so that IntelliJ IDEA can download and run busybox:latest (the latest version of the BusyBox Docker Official Image). Once you have successfully configured an interpreter using Docker, you can go offline.
Note that you cannot install any Python packages into Docker-based project interpreters.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, select SDKs under the Platform Settings section, click , and choose Add Python SDK from the popup menu.
In the left-hand pane of the Add Python Interpreter dialog, select Docker Compose .
Select an existing Docker configuration in the Server dropdown.
Alternatively, click New and perform the following steps to create a new Docker configuration:
Create a Docker configuration
Click New to add a Docker configuration and specify how to connect to the Docker daemon.
The connection settings depend on your Docker version and operating system. For more information, see Docker connection settings.
The Connection successful message should appear at the bottom of the dialog.

The Path mappings table is used to map local folders to corresponding directories in the Docker virtual machine’s file system. Only specified folders will be available for volume binding.
This table is not available on Linux, because when running Docker on Linux, any folder is available for volume binding.
In Configuration files , specify the docker-compose.yml file. Also select the service.

Finally, specify the path to the Python executable:
The configured remote interpreter is added to the list.
For more details about remote Python interpreters, refer to Configure remote Python interpreters.
Removing Python interpreters
If you no longer need a Python interpreter for a project, you can remove it from the project settings.
Navigate to File | Project Structure or press Ctrl+Alt+Shift+S .
In the Project Structure dialog, click SDKs node under Platform Settings .
Choose the interpreter that you want to remove and click .
For any of the configured Python interpreters (but Docker-based), you can:
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Devo Python SDK
This is the SDK to access Devo directly from Python. It can be used to:
- Send events and files to Devo.
- Make queries.
- Manage deferred tasks.
The Devo SDK for Python requires Python 3.7+
- Tested compatibility for python 3.7, 3.8 and 3.9
Installing the SDK
You can install the Devo SDK by using easy_install or pip :
You can use sources files, cloning the project too:
There is specific documentation in the docs folder for each part of SDK:
See PyLibs contributing guide.
Pull and merge requests are welcome ☺
To send data with Devo SDK, first choose the required endpoint depending on the region your are accessing from:
| Region | Endpoint | Port |
|---|---|---|
| USA | collector-us.devo.io | 443 |
| Canada | collector-ca.devo.io | 443 |
| Europe | collector-eu.devo.io | 443 |
| APAC | collector-ap.devo.io | 443 |
You have more information in the official documentation of Devo, Sending data to Devo.
To perform a request with API, first choose the required endpoint depending on the region your are accessing from:
| Region | Endpoint |
|---|---|
| USA | https://apiv2-us.devo.com/search/query |
| Canada | https://apiv2-ca.devo.com/search/query |
| Europe | https://apiv2-eu.devo.com/search/query |
| APAC | https://api-apac.devo.com/search/query |
You have more information in the official documentation of Devo, REST API.
To obtain the access credentials necessary to use this SDK, you must have an account in DEVO.
Check the security credentials info for more details.
You need use a three files (Cert, key and chain) to secure send data to Devo. Administrator users can find them in Administration → Credentials, in the X.509 tab.
You can use a domain API key and API secret to sign the request. These are are a pair of credentials that every Devo account owns. Administrator users can find them in Administration → Credentials, in the Access Keys tab.
You can run tests from the main folder of SDK To launch this script, you need either the environment variables loaded in the system, or the environment.env file in the root of the SDK with the correct values, since to test all the SDK functionalities it is necessary to connect to Devo for the tests of sending and extracting data. There is an example file called environment.env.example
Its normal, by the way, TCP tests fails in clients or not Devo developers systems.
You can add option «Coverage» for create HTML report about tests.
You can also run the test for just one module. This is a useful feature if you are developing functionality in just one module.
You can also exclude one or several tests with -M parameter:
Using the —help flag prints the available modules to use:
- API_CLI: API Command-line interface tests.
- API_QUERY: Query API tests.
- API_TASKS: Task API tests.
- API_ERRORS: Managing of API Errors tests.
- API_PARSER_DATE: Parsing of dates in API tests.
- API_PROCESSORS: Response processors in API tests.
- API_KEEPALIVE: Keep Alive functionality in API tests.
- COMMON_CONFIGURATION: Configuration tests.
- COMMON_DATE_PARSER: Date parser tests.
- SENDER_CLI: Lookup command-line interface tests.
- SENDER_CSV: Lookup uploading through CSV tests.
- SENDER_NUMBER_LOOKUP: Numbers in lookup tests
- SENDER_SEND_DATA: Data sending tests.
- SENDER_SEND_LOOKUP: Lookup sending tests.
Run using Unittest command
You can see references in unittest documentation
For commands like:
If you launch this command from the root directory of the SDK, you need to have the environment variables in your system for all the tests that require connection to Devo can work, not being able to use the environment.env file as in the script.
(C) 2022 Devo, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.