Create a Post
cancel
Showing results for 
Search instead for 
Did you mean: 
Roberts12
Explorer
Jump to solution

python api script

Hi,

I have installed latest version of checkpoint mgmt R81.20 in a test environment and want to use the latest API: https://sc1.checkpoint.com/documents/latest/APIs/#introduction~v1.9%20

I want to automate some tasks using python script from my desktop pc, not run the script directly on checkpoint gateway. I tried with checkpoints official python SDK: https://github.com/CheckPointSW/cp_mgmt_api_python_sdk

But the API commands for the python SDK do not match with the latest Management API Reference v1.9 from checkpoint?

For example from python sdk example:

add_rule_response = client.api_call("add-access-rule",
{"name": rule_name, "layer": "Network", "position": "top"})

 

and example from Management API Reference v1.9:

Command

add access-rule layer "Network" position 1 name "Rule 1" service.1 "SMTP" service.2 "AOL" vpn "MyIntranet"

 

And also I do not find in the documentation for the python SDK all the avaible commands and how to handle session etc. Since the commands are not identical I wonder how to proceed.

 

Please advice and help me get started.

 

If i want to use latest Management API Reference v1.9, should i instead use web api in the python script instead of the python sdk?

Regards

0 Kudos
1 Solution

Accepted Solutions
Nüüül
Advisor
Advisor

Hello,

i believe you mixed up the different ways to leverage the api. 

"add-access-rule" uses web service

"add access-rule" uses the mgmt cli (which is calling API too but is called via cli at management server)

you can switch between them in the documentation - see attached screenshot.
When you are logging in into the API, a session id is generated and sent back to you as response. This session id you will need to add at the following request´s header.

 

Example for callin web API with SDK:

 

 

with APIClient(client_args) as client:
    # If Error occurs due to fingerprint mismatch
    if client.check_fingerprint() is False:
        #output_text.update({"Message":"Could not get the server's fingerprint - Check connectivity with the server."})
        print("UNKNOWN! Logging into SMS not successful! Please troubleshoot/debug script! "+str(output_text))
        raise SystemExit()
    # login to server:
    login_res = client.login(api_user, api_pwd)

 

 

 

so:

documentation is acurate - when using the correct way to call the api

SDK simplifies things like session handling - to understand all the things, you can manually write https requests towards the API with correct headers and so.

 

in case you need help, feel free to reach out

View solution in original post

17 Replies
StuartGreen
Employee
Employee

Hi, I would start with the REST API and use something simple like Python requests to manage the connections. I've worked on several projects recently and didn't need the full SDK. Depending on what you're trying to work on, you might find that something like Ansible is more convenient for you. There are some examples of both approaches here https://developer.checkpoint.com or I've used a simple wrapper package here https://github.com/chkp-stuartgreen/policy-automation-poc/blob/main/packages/simplecpapi.py where I didn't want the full SDK, but didn't want to repeat lots of code either. 

Matlu
MVP Silver
MVP Silver

Hello,
Is it possible to automate tasks using only a Python script that interacts with the Check Point (SMS) product API—for example, to create bulk objects such as IP addresses, domains, and hashes, and add them to groups that have already been created in SmartConsole?
Thank you for your feedback.

0 Kudos
Nüüül
Advisor
Advisor

Not sure what you intend with hashes (ioc?), for the rest - Yes

 

0 Kudos
Matlu
MVP Silver
MVP Silver

Is there any advice on “when to start using Ansible for automation tasks”?
I’m currently testing automation using only Python scripts that leverage the Check Point API, but is there a significant difference when it comes to using Ansible to automate tasks, or does it just come down to personal preference?

0 Kudos
Nüüül
Advisor
Advisor

Ansible basically depends on and is using the api. Personally i‘d say yes, personal preferences and like „company baselines/policies“ (if existent)

imho - Automating repetetive tasks is better using ansible. But If you have tasks based on more complex things (like check something and if A, then do B, or lots of loops ) i‘d stick to a script using the api. 

0 Kudos
Matlu
MVP Silver
MVP Silver

In your experience, if you have repetitive tasks every day—such as creating many IP addresses or domains labeled as “malicious” and adding them to a group of objects that are already in your SmartConsole—
for this type of activity, do you prefer to use a Python script via the API, or do you prefer to use Ansible?

0 Kudos
Nüüül
Advisor
Advisor

Is there a reason for not using network feeds? Like saving a list i.e. in a git repo and let network feed do the rest? 

nevertheless, if you plan to use that longer, i would say ansible. Keep in mind that you will Not only have to add objects but also remove them when not longer needed. Otherwise the database would fill up with unnecessary objects. 

 

0 Kudos
Matlu
MVP Silver
MVP Silver

Please correct me if I'm wrong, but as far as I know, NETWORK Feeds doesn't work in VSX environments.

0 Kudos
Nüüül
Advisor
Advisor

According to https://support.checkpoint.com/results/sk/sk79700 Network Feeds Are supported starting with R82

(was not able to test/validate, as no vsx system on hand)

0 Kudos
Duane_Toler
MVP Silver
MVP Silver

Hi!  Yes, there is.   Python scripts are fine, as are shell scripts.  Switching to Ansible gives you much more, however:

* Consistency: Happens the same way every time

* Predictability: No need to worry about the "how"; just the "what"

* Auditable: Combine with git version control, everything is in the open, and others can read it easily; it's all YAML.

* (Relatively) Rapid deployment: No need to do major re-code for a new capability

* Less "cognitive load": Edit YAML config, save, run, done.

* Burden of maintenance shift: You no longer worry about the "plumbing"; you only worry about what you need to accomplish 

* Idempotency: Only things that need changing are changed; existing items with existing configurations matching the provided configuration are checked, but untouched.

 

With Ansible, you can create yourself a collection of templates with the base outline of everything you need to get started. You can easily collect Before/After evidence for change control, track it all with git, optionally run the playbooks through Docker (increased auditability and consistency).  The platform manages the back-end coding, you worry about the order-of-operations and tasks.  You work with Ansible's constructs:

* Here's a list of host objects I made (these are stored in an external variables file)

* Run these objects through a pre-made task loop to collect their current details (e.g.: Name, IP address, list of group membership; or "Host Foo does not exist")
* Run these objects through a loop to add/remove them based on the definition of the items in the list
* Run these objects through the pre-made task again to collect the fact that they're now deleted (or new objects added)
* Publish changes (or Discard all changes, if just want to test)
* Verify policy (if Published); save result of verification
* Install policy (if Published and Verified); Save result of install
* Create zip file of all Before/After evidence

The initial "hard work" was 1-time setup work to design your outline.  After that, the only thing you need to do is just define your list of objects (hosts, networks, groups, access rules, custom application sites; whatever).  But this shifts your focus; you're no longer banging through Python scripts with the SDK *AND* setting up your input constructs.

I say this next part because you already do Python, so you'll understand it : Ansible natively accepts JSON or YAML as input variables. You don't need to deal with unstructured inputs like CSV or random text files.  YAML is your structured data.  You can instead shift your focus even further and learn how to transform other data input with JQ (or feel free to write another Python script) to emit structured JSON (or, hilariously, transform data back to CSV for "some people" to read).  Data transformation becomes your new skill, (random structure to JSON, convert JSON to YAML) because this is your input vector for Ansible.  Pair that with your playbook template, and run it.

 

*Self-promotion*: Check my signature below for a YouTube series I've made that tells you everything you need to know to get started with Ansible and Check Point. Feel free to PM or e-mail me with any questions!  I also have  GitHub repo setup that you can clone that gets you started with the template design described in the series. 

https://github.com/duanetoler/edge-case-ansible-series/

(Edit: add idempotency above)

--
Ansible for Check Point APIs series: https://www.youtube.com/@EdgeCaseScenario and Substack
(1)
Matlu
MVP Silver
MVP Silver

Hi 🙂

Can Ansible use any type of source?
For example, could you automate a task based on a preventive security posture?

Here’s an example:
If you have a 10.120.0.0/24 network attempting to access an SRV 192.168.10.200/32 via FTP, and this generates a LOG entry such as ACCEPT, could we use Ansible to take a somewhat “reactive” action?
In other words, if an ACCEPT log has already been generated where that traffic is seen as allowed, could Ansible generate an action to create a rule that denies this traffic activity?

Is Ansible an option for this type of scenario?

Thank you

0 Kudos
Nüüül
Advisor
Advisor

Ansible is „only“ the way you get the objects created and so on. The logic before (if log tells this or that) will have to be made beforehands or be done manually by filling the source which is referenced in your ansible playbook.

 

what you just wrote sounds a Bit like Check Points playblocks.

0 Kudos
Duane_Toler
MVP Silver
MVP Silver

No, what you describe is a SIEM or something similar.  Ansible is not a process that runs to monitor activity and take action.  Ansible is an automation and orchestration platform that to execute changes based on configuration data you provide.

--
Ansible for Check Point APIs series: https://www.youtube.com/@EdgeCaseScenario and Substack
Hugo_vd_Kooij
MVP Gold
MVP Gold

To be honest we have not yet used ansible to to do anything related to the policy. But we use Ansible to do these things:

  1. Backup Gaia configuration of all Check Point (virtual) appliances
  2. Backup SmartCenter/SmartEvent/MDS
  3. Verify and enforce the base line which biascally follows the CIS Benchmark 1.1 with a few minor deviations

We do this every day for the full managed stack of Check Point appliances.

<< We make miracles happen while you wait. The impossible jobs take just a wee bit longer. >>
0 Kudos
Nüüül
Advisor
Advisor

Hello,

i believe you mixed up the different ways to leverage the api. 

"add-access-rule" uses web service

"add access-rule" uses the mgmt cli (which is calling API too but is called via cli at management server)

you can switch between them in the documentation - see attached screenshot.
When you are logging in into the API, a session id is generated and sent back to you as response. This session id you will need to add at the following request´s header.

 

Example for callin web API with SDK:

 

 

with APIClient(client_args) as client:
    # If Error occurs due to fingerprint mismatch
    if client.check_fingerprint() is False:
        #output_text.update({"Message":"Could not get the server's fingerprint - Check connectivity with the server."})
        print("UNKNOWN! Logging into SMS not successful! Please troubleshoot/debug script! "+str(output_text))
        raise SystemExit()
    # login to server:
    login_res = client.login(api_user, api_pwd)

 

 

 

so:

documentation is acurate - when using the correct way to call the api

SDK simplifies things like session handling - to understand all the things, you can manually write https requests towards the API with correct headers and so.

 

in case you need help, feel free to reach out

Roberts12
Explorer

Thank you for the explanation! if you have more examples to share it would be appreciated.
I can run the example scripts from the github repo, but when I extend the script with more functions and more API calls I get this error message: 
Failed to add the access-rule: '1', Error:
code: generic_err_wrong_session_id
message: Wrong session id [XwGUCgAvdFDB2_8vTN2KBXV-XCynk4Zp12Q]. Session may be expired. Please check session id and resend the request

0 Kudos
Nüüül
Advisor
Advisor

I wrote some scripts leveraging the SDK - like: https://github.com/leinadred/CP_IPS-Update-Monitoring4Nagios or https://github.com/leinadred/py_cp-updatable-objects

difficult to say, without being able to see your script. but i think you went out of the "with" procedure, so SDK logged you out. As API is "opened" like a file, with is closing it (and logs off the connection) when leaving the file.

 

So your "working procedures" will have to be inside of the "opened file"

in https://github.com/leinadred/py_cp-updatable-objects from line 59 (res_repo =....)

 

0 Kudos

Leaderboard

Epsum factorial non deposit quid pro quo hic escorol.

Upcoming Events

    CheckMates Events