Fanatsorana ny API Check Point miaraka amin'ny Python SDK

Fanatsorana ny API Check Point miaraka amin'ny Python SDKNy hery feno amin'ny fifandraisana amin'ny API dia miseho rehefa ampiasaina miaraka amin'ny kaody programa, rehefa azo atao ny mamorona fangatahana API sy fitaovana amin'ny famakafakana ny valin'ny API. Na izany aza, mbola mijanona ho tsy hita Kit Fampandrosoana Software Python (antsoina hoe Python SDK) ho an'ny Check Point Management API, fa zava-poana. Manamora ny fiainan'ny mpamorona sy ny mpankafy automatique izany. Nahazo laza be i Python tato ho ato ary nanapa-kevitra ny hameno ny banga aho ary hamerina hijery ireo endri-javatra fototra. Check Point API Python Development Kit. Ity lahatsoratra ity dia manampy tsara amin'ny lahatsoratra hafa momba ny Habré Check Point R80.10 API. Fitantanana amin'ny alàlan'ny CLI, scripts ary maro hafa. Hojerentsika ny fomba fanoratana script mampiasa ny Python SDK ary hijery akaiky ny fiasa vaovao Management API amin'ny version 1.6 (tohanana manomboka amin'ny R80.40). Mba hahatakarana ny lahatsoratra dia mila fahalalana fototra momba ny fiasana amin'ny API sy Python ianao.

Check Point dia mazoto mamolavola ny API ary amin'izao fotoana izao dia navoaka ireto manaraka ireto:

Ny Python SDK amin'izao fotoana izao dia manohana ny fifandraisana amin'ny Management API sy Gaia API. Hojerentsika ireo kilasy, fomba ary fari-piainana manan-danja indrindra ato amin'ity module ity.

Fanatsorana ny API Check Point miaraka amin'ny Python SDK

Fametrahana ny module

Module cpapi mametraka haingana sy mora avy amin'ny tahiry ofisialy Check Point amin'ny github miaraka amin'ny fanampian'ny pip. Misy torolàlana fametrahana amin'ny antsipiriany ao README.md. Ity maody ity dia namboarina mba hiasa amin'ny Python version 2.7 sy 3.7. Amin'ity lahatsoratra ity dia homena ohatra amin'ny fampiasana Python 3.7. Na izany aza, ny Python SDK dia azo alefa mivantana avy amin'ny Check Point Management Server (Smart Management), fa ny Python 2.7 ihany no manohana azy, ka ny fizarana farany dia hanome code ho an'ny version 2.7. Avy hatrany aorian'ny fametrahana ny module dia manoro hevitra aho hijery ireo ohatra ao amin'ny lahatahiry examples_python2 и examples_python3.

fanombohana

Mba hahafahantsika miasa miaraka amin'ireo singa ao amin'ny module cpapi dia mila manafatra avy amin'ny module cpapi kilasy roa farafahakeliny ilaina:

APIClient и APIClientArgs

from cpapi import APIClient, APIClientArgs

kilasy APIClientArgs dia tompon'andraikitra amin'ny masontsivana fifandraisana amin'ny mpizara API, ary ny kilasy APIClient dia tompon'andraikitra amin'ny fifandraisana amin'ny API.

Famaritana ny mari-pamantarana fifandraisana

Mba hamaritana masontsivana isan-karazany hifandraisana amin'ny API dia mila mamorona ohatra momba ny kilasy ianao APIClientArgs. Amin'ny ankapobeny, ny masontsivana dia efa voafaritra mialoha ary rehefa mihazakazaka ny script amin'ny mpizara fanaraha-maso dia tsy mila voafaritra izy ireo.

client_args = APIClientArgs()

Saingy rehefa mihazakazaka amin'ny mpampiantrano antoko fahatelo ianao dia mila mamaritra farafaharatsiny ny adiresy IP na ny anaran'ny mpampiantrano ny mpizara API (fantatra ihany koa amin'ny hoe mpizara fitantanana). Amin'ny ohatra etsy ambany, dia mamaritra ny mari-pamantarana fifandraisana amin'ny mpizara izahay ary manome azy ny adiresy IP an'ny mpizara fitantanana ho toy ny tady.

client_args = APIClientArgs(server='192.168.47.241')

Andeha hojerentsika ny mari-pamantarana rehetra sy ny soatoavina mahazatra azo ampiasaina rehefa mifandray amin'ny mpizara API:

Arguments amin'ny fomba __init__ an'ny kilasy APIClientArgs

class APIClientArgs:
    """
    This class provides arguments for APIClient configuration.
    All the arguments are configured with their default values.
    """

    # port is set to None by default, but it gets replaced with 443 if not specified
    # context possible values - web_api (default) or gaia_api
    def __init__(self, port=None, fingerprint=None, sid=None, server="127.0.0.1", http_debug_level=0,
                 api_calls=None, debug_file="", proxy_host=None, proxy_port=8080,
                 api_version=None, unsafe=False, unsafe_auto_accept=False, context="web_api"):
        self.port = port
        # management server fingerprint
        self.fingerprint = fingerprint
        # session-id.
        self.sid = sid
        # management server name or IP-address
        self.server = server
        # debug level
        self.http_debug_level = http_debug_level
        # an array with all the api calls (for debug purposes)
        self.api_calls = api_calls if api_calls else []
        # name of debug file. If left empty, debug data will not be saved to disk.
        self.debug_file = debug_file
        # HTTP proxy server address (without "http://")
        self.proxy_host = proxy_host
        # HTTP proxy port
        self.proxy_port = proxy_port
        # Management server's API version
        self.api_version = api_version
        # Indicates that the client should not check the server's certificate
        self.unsafe = unsafe
        # Indicates that the client should automatically accept and save the server's certificate
        self.unsafe_auto_accept = unsafe_auto_accept
        # The context of using the client - defaults to web_api
        self.context = context

Mino aho fa ny tohan-kevitra azo ampiasaina amin'ny kilasy APIClientArgs dia intuitive amin'ny mpitantana Check Point ary tsy mitaky fanehoan-kevitra fanampiny.

Mampifandray amin'ny alàlan'ny APIClient sy ny mpitantana ny contexte

kilasy APIClient Ny fomba mora indrindra hampiasana azy dia amin'ny alàlan'ny mpitantana ny contexte. Ny hany mila ampitaina amin'ny ohatra iray amin'ny kilasy APIClient dia ny mari-pamantarana fifandraisana izay nofaritana tamin'ny dingana teo aloha.

with APIClient(client_args) as client:

Ny mpitantana ny contexte dia tsy hanao antso ho azy amin'ny fidirana amin'ny mpizara API, fa hanao antso hivoaka izy rehefa mivoaka azy. Raha toa ka tsy ilaina ny fidirana rehefa vita ny fiasàna amin'ny antso API, dia mila manomboka miasa ianao nefa tsy mampiasa ny mpitantana ny contexte:

client = APIClient(clieng_args)

Fitsapana fifandraisana

Ny fomba tsotra indrindra hanamarinana raha mahafeno ny mari-pamantarana voafaritra ny fifandraisana dia ny fampiasana ny fomba check_fingerprint. Raha tsy nahomby ny fanamarinana ny fitambaran'ny hash sha1 ho an'ny fanondron'ny taratasy fanamarinana API mpizara (naverina ny fomba Diso), dia matetika vokatry ny olana amin'ny fifandraisana izany ary azontsika atao ny mampiato ny fanatanterahana ny programa (na manome ny mpampiasa ny fahafahana hanitsy ny angon-drakitra fifandraisana):

    if client.check_fingerprint() is False:
        print("Could not get the server's fingerprint - Check connectivity with the server.")
        exit(1)

Mariho fa amin'ny ho avy ny kilasy APIClient dia hanamarina ny antso rehetra API (methods api_call и api_query, hiresaka momba azy ireo bebe kokoa isika) mari-pankasitrahana sha1 fingerprint amin'ny mpizara API. Fa raha, rehefa manamarina ny sha1 fingerprint amin'ny taratasy fanamarinana mpizara API, dia hita ny fahadisoana (tsy fantatra na niova ny taratasy fanamarinana), ny fomba check_fingerprint dia hanome fahafahana hanampy / hanova ny vaovao momba izany amin'ny milina eo an-toerana ho azy. Ity fanamarinana ity dia mety ho kilemaina tanteraka (saingy izany dia azo atolotra raha tsy misy ny script ao amin'ny server API mihitsy, rehefa mifandray amin'ny 127.0.0.1), amin'ny fampiasana ny argument APIClientArgs - unsafe_auto_accept (jereo bebe kokoa momba ny APIClientArgs teo aloha ao amin'ny "Famaritana ny mari-pamantarana fifandraisana").

client_args = APIClientArgs(unsafe_auto_accept=True)

Midira amin'ny mpizara API

У APIClient Misy fomba 3 ho an'ny fidirana amin'ny mpizara API, ary ny tsirairay amin'izy ireo dia mahatakatra ny dikany Sid(session-id), izay ampiasaina ho azy amin'ny fiantsoana API tsirairay ao amin'ny lohapejy (ny anarana ao amin'ny lohatenin'ity parameter ity dia X-chkp-sid), noho izany dia tsy ilaina ny fanodinana bebe kokoa ity parameter ity.

fomba fidirana

Safidy amin'ny fampiasana ny fidirana sy ny tenimiafina (amin'ny ohatra, ny solonanarana admin sy ny tenimiafina 1q2w3e dia alefa ho tohan-kevitra momba ny toerana):

     login = client.login('admin', '1q2w3e')  

Misy ihany koa ny masontsivana fanampiny azo alaina amin'ny fomba fidirana; ireto ny anarany sy ny sandany mahazatra:

continue_last_session=False, domain=None, read_only=False, payload=None

Method login_with_api_key

Safidy mampiasa fanalahidin'ny api (atomboka amin'ny dikan-teny fitantanana R80.40/Management API v1.6, "3TsbPJ8ZKjaJGvFyoFqHFA==" ity no sanda fanalahidin'ny API ho an'ny mpampiasa iray ao amin'ny lohamilina fitantanana miaraka amin'ny fomba fanomezan-dàlana fanalahidy API):

     login = client.login_with_api_key('3TsbPJ8ZKjaJGvFyoFqHFA==') 

Amin'ny fomba login_with_api_key ny masontsivana azo atao mitovy amin'ny fomba Hiditra.

login_as_root fomba

Safidy hiditra amin'ny milina eo an-toerana miaraka amin'ny mpizara API:

     login = client.login_as_root()

Tsy misy afa-tsy masontsivana roa azo ampiasaina amin'ity fomba ity:

domain=None, payload=None

Ary farany dia miantso ny tenany ny API

Manana safidy roa izahay hanaovana antso API amin'ny alàlan'ny fomba api_call и api_query. Andeha hojerentsika hoe inona no maha samy hafa azy ireo.

api_call

Ity fomba ity dia azo ampiharina amin'ny antso rehetra. Mila mandalo ny ampahany farany amin'ny antso api sy ny enta-mavesatra ao amin'ny vatana fangatahana isika raha ilaina. Raha foana ny entana dia tsy azo afindra mihitsy:

api_versions = client.api_call('show-api-versions') 

Output ho an'ity fangatahana ity eo ambanin'ny fanapahana:

In [23]: api_versions                                                           
Out[23]: 
APIResponse({
    "data": {
        "current-version": "1.6",
        "supported-versions": [
            "1",
            "1.1",
            "1.2",
            "1.3",
            "1.4",
            "1.5",
            "1.6"
        ]
    },
    "res_obj": {
        "data": {
            "current-version": "1.6",
            "supported-versions": [
                "1",
                "1.1",
                "1.2",
                "1.3",
                "1.4",
                "1.5",
                "1.6"
            ]
        },
        "status_code": 200
    },
    "status_code": 200,
    "success": true
})
show_host = client.api_call('show-host', {'name' : 'h_8.8.8.8'})

Output ho an'ity fangatahana ity eo ambanin'ny fanapahana:

In [25]: show_host                                                              
Out[25]: 
APIResponse({
    "data": {
        "color": "black",
        "comments": "",
        "domain": {
            "domain-type": "domain",
            "name": "SMC User",
            "uid": "41e821a0-3720-11e3-aa6e-0800200c9fde"
        },
        "groups": [],
        "icon": "Objects/host",
        "interfaces": [],
        "ipv4-address": "8.8.8.8",
        "meta-info": {
            "creation-time": {
                "iso-8601": "2020-05-01T21:49+0300",
                "posix": 1588358973517
            },
            "creator": "admin",
            "last-modifier": "admin",
            "last-modify-time": {
                "iso-8601": "2020-05-01T21:49+0300",
                "posix": 1588358973517
            },
            "lock": "unlocked",
            "validation-state": "ok"
        },
        "name": "h_8.8.8.8",
        "nat-settings": {
            "auto-rule": false
        },
        "read-only": false,
        "tags": [],
        "type": "host",
        "uid": "c210af07-1939-49d3-a351-953a9c471d9e"
    },
    "res_obj": {
        "data": {
            "color": "black",
            "comments": "",
            "domain": {
                "domain-type": "domain",
                "name": "SMC User",
                "uid": "41e821a0-3720-11e3-aa6e-0800200c9fde"
            },
            "groups": [],
            "icon": "Objects/host",
            "interfaces": [],
            "ipv4-address": "8.8.8.8",
            "meta-info": {
                "creation-time": {
                    "iso-8601": "2020-05-01T21:49+0300",
                    "posix": 1588358973517
                },
                "creator": "admin",
                "last-modifier": "admin",
                "last-modify-time": {
                    "iso-8601": "2020-05-01T21:49+0300",
                    "posix": 1588358973517
                },
                "lock": "unlocked",
                "validation-state": "ok"
            },
            "name": "h_8.8.8.8",
            "nat-settings": {
                "auto-rule": false
            },
            "read-only": false,
            "tags": [],
            "type": "host",
            "uid": "c210af07-1939-49d3-a351-953a9c471d9e"
        },
        "status_code": 200
    },
    "status_code": 200,
    "success": true
})

api_query

Mamelà ahy hanao famandrihana avy hatrany fa ity fomba ity dia tsy azo ampiharina afa-tsy amin'ny antso izay ahitana offset ny vokatra. Ny fanatsoahan-kevitra toy izany dia mitranga rehefa misy na mety misy fampahalalana be dia be. Ohatra, mety ho fangatahana lisitry ny zavatra fampiantranoana noforonina rehetra ao amin'ny lohamilina fitantanana. Ho an'ny fangatahana toy izany, ny API dia mamerina lisitry ny zavatra 50 amin'ny alàlan'ny default (azonao atao ny mampitombo ny fetra ho zavatra 500 amin'ny valiny). Ary mba tsy hisintonana ny fampahalalana imbetsaka, hanova ny mari-pamantarana offset amin'ny fangatahana API, dia misy fomba api_query izay manao izany ho azy. Ohatra amin'ny antso izay ilaina ity fomba ity: seho-sessions, fampiantranoana fampisehoana, tambajotra-seho, fampisehoana-wildcards, vondrona-fampisehoana, laharan'ny adiresin'ny fampisehoana, vavahadin-tseza-tsotsotra, fampisehoana-vondrona-tsotra, anjara-fidirana-fampisehoana, mpanjifa azo itokisana, fampisehoana-fonosana. Raha ny marina dia mahita teny maro amin'ny anaran'ireo antso API ireo izahay, ka ho mora kokoa ny fiantsoana ireo antso ireo api_query

show_hosts = client.api_query('show-hosts') 

Output ho an'ity fangatahana ity eo ambanin'ny fanapahana:

In [21]: show_hosts                                                             
Out[21]: 
APIResponse({
    "data": [
        {
            "domain": {
                "domain-type": "domain",
                "name": "SMC User",
                "uid": "41e821a0-3720-11e3-aa6e-0800200c9fde"
            },
            "ipv4-address": "192.168.47.1",
            "name": "h_192.168.47.1",
            "type": "host",
            "uid": "5d7d7086-d70b-4995-971a-0583b15a2bfc"
        },
        {
            "domain": {
                "domain-type": "domain",
                "name": "SMC User",
                "uid": "41e821a0-3720-11e3-aa6e-0800200c9fde"
            },
            "ipv4-address": "8.8.8.8",
            "name": "h_8.8.8.8",
            "type": "host",
            "uid": "c210af07-1939-49d3-a351-953a9c471d9e"
        }
    ],
    "res_obj": {
        "data": {
            "from": 1,
            "objects": [
                {
                    "domain": {
                        "domain-type": "domain",
                        "name": "SMC User",
                        "uid": "41e821a0-3720-11e3-aa6e-0800200c9fde"
                    },
                    "ipv4-address": "192.168.47.1",
                    "name": "h_192.168.47.1",
                    "type": "host",
                    "uid": "5d7d7086-d70b-4995-971a-0583b15a2bfc"
                },
                {
                    "domain": {
                        "domain-type": "domain",
                        "name": "SMC User",
                        "uid": "41e821a0-3720-11e3-aa6e-0800200c9fde"
                    },
                    "ipv4-address": "8.8.8.8",
                    "name": "h_8.8.8.8",
                    "type": "host",
                    "uid": "c210af07-1939-49d3-a351-953a9c471d9e"
                }
            ],
            "to": 2,
            "total": 2
        },
        "status_code": 200
    },
    "status_code": 200,
    "success": true
})

Fikarakarana ny valin'ny antso API

Aorian'izany dia azonao atao ny mampiasa ny variables sy ny fomba fiasan'ny kilasy APIResponse(na ao anatin'ny mpitantana contexte na ivelany). Ao am-pianarana APIResponse Fomba 4 sy variables 5 no voafaritra mialoha; hodinihintsika amin'ny antsipiriany bebe kokoa ny zava-dehibe indrindra.

Fanatsorana ny API Check Point miaraka amin'ny Python SDK

fahombiazana

Hanombohana, hevitra tsara ny manao izay hahazoana antoka fa nahomby ny antso API ary namerina valiny. Misy fomba izany fahombiazana:

In [49]: api_versions.success                                                   
Out[49]: True

Miverina ho Marina raha nahomby ny antso API (kaody valiny - 200) ary diso raha tsy nahomby (kaody valiny hafa). Tsara ny mampiasa avy hatrany aorian'ny antso API hanehoana fampahalalana samihafa miankina amin'ny kaody valiny.

if api_ver.success: 
    print(api_versions.data) 
else: 
    print(api_versions.err_message) 

statuscode

Mamerina ny kaody famaliana rehefa vita ny antso API.

In [62]: api_versions.status_code                                               
Out[62]: 400

Kaody valiny mety: 200,400,401,403,404,409,500,501.

set_success_status

Amin'ity tranga ity, mety ilaina ny manova ny sandan'ny satan'ny fahombiazana. Amin'ny lafiny ara-teknika, azonao atao ny mametraka na inona na inona ao, na dia kofehy mahazatra aza. Fa ny tena ohatra dia ny famerenana ity paramètre ity ho Diso amin'ny fepetra sasany miaraka. Eto ambany, tandremo ny ohatra rehefa misy asa mandeha amin'ny mpizara fitantanana, fa hoheverinay fa tsy nahomby io fangatahana io (apetrakay ny fari-pahombiazana Diso, na dia nahomby aza ny antso API ary namerina ny code 200).

for task in task_result.data["tasks"]:
    if task["status"] == "failed" or task["status"] == "partially succeeded":
        task_result.set_success_status(False)
        break

valiny ()

Ny fomba famaliana dia ahafahanao mijery ny rakibolana miaraka amin'ny kaody valiny (status_code) sy ny vatan'ny valiny (body).

In [94]: api_versions.response()                                                
Out[94]: 
{'status_code': 200,
 'data': {'current-version': '1.6',
  'supported-versions': ['1', '1.1', '1.2', '1.3', '1.4', '1.5', '1.6']}}

tahirin-kevitra

Mamela anao hahita afa-tsy ny vatan'ny valiny (vatana) tsy misy fampahalalana tsy ilaina.

In [93]: api_versions.data                                                      
Out[93]: 
{'current-version': '1.6',
 'supported-versions': ['1', '1.1', '1.2', '1.3', '1.4', '1.5', '1.6']}

error_message

Ity fampahalalana ity dia tsy misy afa-tsy rehefa nisy lesoka teo am-panaovana ny fangatahana API (kaody valiny tsy 200). Output ohatra

In [107]: api_versions.error_message                                            
Out[107]: 'code: generic_err_invalid_parameter_namenmessage: Unrecognized parameter [1]n'

Ohatra mahasoa

Ireto manaraka ireto dia ohatra mampiasa ny antso API izay nampiana tao amin'ny Management API 1.6.

Voalohany, andeha hojerentsika ny fomba fiasan'ny antso add-host и add-address-range. Andeha hatao hoe mila mamorona ny adiresy IP rehetra an'ny subnet 192.168.0.0/24, ny octet farany amin'izany dia 5, ho zavatra amin'ny karazana mpampiantrano, ary soraty ny adiresy IP hafa rehetra ho zavatra amin'ny karazana karazana adiresy. Amin'ity tranga ity, esory ny adiresy subnet sy ny adiresy fandefasana.

Noho izany, eto ambany ny script izay mamaha ity olana ity ary mamorona zavatra 50 amin'ny karazana mpampiantrano ary zavatra 51 amin'ny karazana adiresy. Mba hamahana ny olana dia ilaina ny antso API 101 (tsy manisa ny antso famoahana farany). Ary koa, amin'ny fampiasana ny maody timeit, kajy ny fotoana ilaina hanatanterahana ny script mandra-pamoahan'ny fanovana.

Script mampiasa add-host sy add-address-range

import timeit
from cpapi import APIClient, APIClientArgs

start = timeit.default_timer()

first_ip = 1
last_ip = 4

client_args = APIClientArgs(server="192.168.47.240")

with APIClient(client_args) as client: 
     login = client.login_with_api_key('3TsbPJ8ZKjaJGvFyoFqHFA==')
     for ip in range(5,255,5):
         add_host = client.api_call("add-host", {"name" : f"h_192.168.0.{ip}", "ip-address": f'192.168.0.{ip}'})
     while last_ip < 255:
         add_range = client.api_call("add-address-range", {"name": f"r_192.168.0.{first_ip}-{last_ip}", "ip-address-first": f"192.168.0.{first_ip}", "ip-address-last": f"192.168.0.{last_ip}"})
         first_ip+=5
         last_ip+=5
     stop = timeit.default_timer() 
     publish = client.api_call("publish")
     
print(f'Time to execute batch request: {stop - start} seconds')

Ao amin'ny tontolon'ny laboratoara, ity script ity dia mila 30 ka hatramin'ny 50 segondra hanatanterahana, miankina amin'ny enta-mavesatry ny mpizara fitantanana.

Andeha hojerentsika ny fomba hamahana ny olana mitovy amin'ny fampiasana antso API add-objects-batch, fanohanana izay nampiana tao amin'ny API version 1.6. Ity antso ity dia ahafahanao mamorona zavatra maro indray mandeha amin'ny fangatahana API iray. Ankoatr'izay, ireo dia mety ho zavatra amin'ny karazana samihafa (ohatra, mpampiantrano, subnets ary adiresy). Noho izany, ny asantsika dia azo voavaha ao anatin'ny rafitry ny antso API iray.

Script mampiasa add-objects-batch

import timeit
from cpapi import APIClient, APIClientArgs

start = timeit.default_timer()

client_args = APIClientArgs(server="192.168.47.240")

objects_list_ip = []
objects_list_range = []

for ip in range(5,255,5):
    data = {"name": f'h_192.168.0.{ip}', "ip-address": f'192.168.0.{ip}'}
    objects_list_ip.append(data)
    
first_ip = 1
last_ip = 4


while last_ip < 255:
    data = {"name": f"r_192.168.0.{first_ip}-{last_ip}", "ip-address-first": f"192.168.0.{first_ip}", "ip-address-last": f"192.168.0.{last_ip}"}
    objects_list_range.append(data)
    first_ip+=5
    last_ip+=5

data_for_batch = {
  "objects" : [ {
    "type" : "host",
    "list" : objects_list_ip
}, {
    "type" : "address-range",
    "list" : objects_list_range
  }]
}


with APIClient(client_args) as client: 
     login = client.login_with_api_key('3TsbPJ8ZKjaJGvFyoFqHFA==')
     add_objects_batch = client.api_call("add-objects-batch", data_for_batch)
     stop = timeit.default_timer() 
     publish = client.api_call("publish")
     
print(f'Time to execute batch request: {stop - start} seconds')

Ary ny fampandehanana ity script ity amin'ny tontolon'ny laboratoara dia mila 3 ka hatramin'ny 7 segondra, miankina amin'ny enta-mavesatry ny mpizara fitantanana. Izany hoe, amin'ny antsalany, amin'ny zavatra API 101, ny antso karazana batch dia mandeha in-10 haingana kokoa. Amin'ny zavatra maro kokoa dia ho manaitra kokoa ny fahasamihafana.

Andeha hojerentsika ny fomba fiasa set-objects-batch. Amin'ny fampiasana an'ity antso API ity dia afaka manova betsaka ny paramètre rehetra isika. Andeha apetraka ny tapany voalohany amin'ireo adiresy avy amin'ny ohatra teo aloha (hatramin'ny .124 mpampiantrano, ary ny salan'isa ihany koa) amin'ny loko sienna, ary asio loko khaki amin'ny tapany faharoa amin'ny adiresy.

Fanovana ny lokon'ny zavatra noforonina tamin'ny ohatra teo aloha

from cpapi import APIClient, APIClientArgs

client_args = APIClientArgs(server="192.168.47.240")

objects_list_ip_first = []
objects_list_range_first = []
objects_list_ip_second = []
objects_list_range_second = []

for ip in range(5,125,5):
    data = {"name": f'h_192.168.0.{ip}', "color": "sienna"}
    objects_list_ip_first.append(data)
    
for ip in range(125,255,5):
    data = {"name": f'h_192.168.0.{ip}', "color": "khaki"}
    objects_list_ip_second.append(data)
    
first_ip = 1
last_ip = 4
while last_ip < 125:
    data = {"name": f"r_192.168.0.{first_ip}-{last_ip}", "color": "sienna"}
    objects_list_range_first.append(data)
    first_ip+=5
    last_ip+=5
    
while last_ip < 255:
    data = {"name": f"r_192.168.0.{first_ip}-{last_ip}", "color": "khaki"}
    objects_list_range_second.append(data)
    first_ip+=5
    last_ip+=5

data_for_batch_first  = {
  "objects" : [ {
    "type" : "host",
    "list" : objects_list_ip_first
}, {
    "type" : "address-range",
    "list" : objects_list_range_first
  }]
}

data_for_batch_second  = {
  "objects" : [ {
    "type" : "host",
    "list" : objects_list_ip_second
}, {
    "type" : "address-range",
    "list" : objects_list_range_second
  }]
}

with APIClient(client_args) as client: 
     login = client.login_with_api_key('3TsbPJ8ZKjaJGvFyoFqHFA==') 
     set_objects_batch_first = client.api_call("set-objects-batch", data_for_batch_first)
     set_objects_batch_second = client.api_call("set-objects-batch", data_for_batch_second)
     publish = client.api_call("publish")

Azonao atao ny mamafa zavatra marobe amin'ny antso API iray mampiasa delete-objects-batch. Andeha hojerentsika ny ohatra kaody iray izay mamafa ny mpampiantrano rehetra noforonina teo aloha add-objects-batch.

Famafana zavatra mampiasa delete-objects-batch

from cpapi import APIClient, APIClientArgs

client_args = APIClientArgs(server="192.168.47.240")

objects_list_ip = []
objects_list_range = []

for ip in range(5,255,5):
    data = {"name": f'h_192.168.0.{ip}'}
    objects_list_ip.append(data)

first_ip = 1
last_ip = 4
while last_ip < 255:
    data = {"name": f"r_192.168.0.{first_ip}-{last_ip}"}
    objects_list_range.append(data)
    first_ip+=5
    last_ip+=5

data_for_batch = {
  "objects" : [ {
    "type" : "host",
    "list" : objects_list_ip
}, {
    "type" : "address-range",
    "list" : objects_list_range
  }]
}

with APIClient(client_args) as client: 
     login = client.login_with_api_key('3TsbPJ8ZKjaJGvFyoFqHFA==')
     delete_objects_batch = client.api_call("delete-objects-batch", data_for_batch)
     publish = client.api_call("publish")

print(delete_objects_batch.data)

Ny fiasa rehetra miseho amin'ny famoahana vaovao momba ny rindrambaiko Check Point dia mahazo avy hatrany ny antso API. Noho izany, tao amin'ny R80.40 dia niseho ny "endri-javatra" toy ny Miverena amin'ny fanavaozana sy ny Smart Task, ary ny antso API mifandraika dia nomanina avy hatrany ho azy ireo. Ankoatr'izay, ny fiasa rehetra rehefa miala amin'ny console Legacy mankany amin'ny maodely Unified Policy dia mahazo fanohanana API ihany koa. Ohatra, ny fanavaozana nandrasana hatry ny ela tao amin'ny dikan-tsarimihetsika R80.40 dia ny fifindran'ny politikan'ny Fanaraha-maso HTTPS avy amin'ny fomba Lova mankany amin'ny maodely Politika Mitambatra, ary nahazo antso API avy hatrany io fampiasa io. Ity misy ohatra iray amin'ny fehezan-dalàna izay manampy fitsipika amin'ny toerana ambony indrindra amin'ny politikan'ny Fanaraha-maso HTTPS izay manilika sokajy 3 amin'ny fisafoana (Fahasalamana, Fitantanam-bola, Sampan-draharaham-panjakana), izay voarara tsy hanao fisafoana araka ny lalàna any amin'ny firenena maromaro.

Manampia fitsipika amin'ny politika Fanaraha-maso HTTPS

from cpapi import APIClient, APIClientArgs

client_args = APIClientArgs(server="192.168.47.240")

data = {
  "layer" : "Default Layer",
  "position" : "top",
  "name" : "Legal Requirements",
  "action": "bypass",
  "site-category": ["Health", "Government / Military", "Financial Services"]
}

with APIClient(client_args) as client: 
     login = client.login_with_api_key('3TsbPJ8ZKjaJGvFyoFqHFA==')
     add_https_rule = client.api_call("add-https-rule", data)
     publish = client.api_call("publish")

Mandeha script Python amin'ny mpizara fitantanana Check Point

Mitovy daholo ny zava-drehetra README.md misy fampahalalana momba ny fomba fampandehanana ny script Python mivantana avy amin'ny mpizara fanaraha-maso. Mety ho mora izany rehefa tsy afaka mifandray amin'ny mpizara API amin'ny milina hafa ianao. Noraisiko horonan-tsary naharitra enina minitra izay nijereko ny fametrahana ilay module cpapi ary endri-javatra amin'ny fampandehanana script Python amin'ny mpizara fanaraha-maso. Ohatra, misy script izay mandeha mandeha ho azy ny fandrindrana ny vavahady vaovao ho an'ny asa toy ny fanaraha-maso ny tambajotra Security CheckUp. Anisan'ireo endri-javatra tsy maintsy niatrehana aho: ny fiasa dia tsy mbola niseho tao amin'ny Python 2.7 fahan'ny, ka mba handrafetana ny vaovao ampidirin'ny mpampiasa dia misy fiasa iray ampiasaina raw_input. Raha tsy izany, ny kaody dia mitovy amin'ny fandefasana avy amin'ny milina hafa, fa mety kokoa ny mampiasa ny asa login_as_root, mba tsy hanondroana ny solonanaranao manokana, ny tenimiafinao ary ny adiresy IP an'ny mpizara fitantanana indray.

Script ho an'ny fametrahana haingana ny Security CheckUp

from __future__ import print_function
import getpass
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from cpapi import APIClient, APIClientArgs

def main():
    with APIClient() as client:
       # if client.check_fingerprint() is False:
       #     print("Could not get the server's fingerprint - Check connectivity with the server.")
       #     exit(1)
        login_res = client.login_as_root()

        if login_res.success is False:
            print("Login failed:n{}".format(login_res.error_message))
            exit(1)

        gw_name = raw_input("Enter the gateway name:")
        gw_ip = raw_input("Enter the gateway IP address:")
        if sys.stdin.isatty():
            sic = getpass.getpass("Enter one-time password for the gateway(SIC): ")
        else:
            print("Attention! Your password will be shown on the screen!")
            sic = raw_input("Enter one-time password for the gateway(SIC): ")
        version = raw_input("Enter the gateway version(like RXX.YY):")
        add_gw = client.api_call("add-simple-gateway", {'name' : gw_name, 'ipv4-address' : gw_ip, 'one-time-password' : sic, 'version': version.capitalize(), 'application-control' : 'true', 'url-filtering' : 'true', 'ips' : 'true', 'anti-bot' : 'true', 'anti-virus' : 'true', 'threat-emulation' : 'true'})
        if add_gw.success and add_gw.data['sic-state'] != "communicating":
            print("Secure connection with the gateway hasn't established!")
            exit(1)
        elif add_gw.success:
            print("The gateway was added successfully.")
            gw_uid = add_gw.data['uid']
            gw_name = add_gw.data['name']
        else:
            print("Failed to add the gateway - {}".format(add_gw.error_message))
            exit(1)

        change_policy = client.api_call("set-access-layer", {"name" : "Network", "applications-and-url-filtering": "true", "content-awareness": "true"})
        if change_policy.success:
            print("The policy has been changed successfully")
        else:
            print("Failed to change the policy- {}".format(change_policy.error_message))
        change_rule = client.api_call("set-access-rule", {"name" : "Cleanup rule", "layer" : "Network", "action": "Accept", "track": {"type": "Detailed Log", "accounting": "true"}})
        if change_rule.success:
            print("The cleanup rule has been changed successfully")
        else:
            print("Failed to change the cleanup rule- {}".format(change_rule.error_message))

        # publish the result
        publish_res = client.api_call("publish", {})
        if publish_res.success:
            print("The changes were published successfully.")
        else:
                print("Failed to publish the changes - {}".format(install_tp_policy.error_message))

        install_access_policy = client.api_call("install-policy", {"policy-package" : "Standard", "access" : 'true',  "threat-prevention" : 'false', "targets" : gw_uid})
        if install_access_policy.success:
            print("The access policy has been installed")
        else:
                print("Failed to install access policy - {}".format(install_tp_policy.error_message))

        install_tp_policy = client.api_call("install-policy", {"policy-package" : "Standard", "access" : 'false',  "threat-prevention" : 'true', "targets" : gw_uid})
        if install_tp_policy.success:
            print("The threat prevention policy has been installed")
        else:
            print("Failed to install threat prevention policy - {}".format(install_tp_policy.error_message))
        
        # add passwords and passphrases to dictionary
        with open('additional_pass.conf') as f:
            line_num = 0
            for line in f:
                line_num += 1
                add_password_dictionary = client.api_call("run-script", {"script-name" : "Add passwords and passphrases", "script" : "printf "{}" >> $FWDIR/conf/additional_pass.conf".format(line), "targets" : gw_name})
                if add_password_dictionary.success:
                    print("The password dictionary line {} was added successfully".format(line_num))
                else:
                    print("Failed to add the dictionary - {}".format(add_password_dictionary.error_message))

main()

Ohatra iray misy rakibolana tenimiafina additional_pass.conf
{
"passwords" : ["malware","malicious","infected","Infected"],
"phrases" : ["password","Password","Pass","pass","codigo","key","pwd","пароль","Пароль","Ключ","ключ","шифр","Шифр"] }

famaranana

Ity lahatsoratra ity dia mandinika afa-tsy ireo fahafaha-manao fototra amin'ny asa Python SDK ary module cpapi(araka ny efa novinavinainao fa tena mitovy ireo teny ireo), ary amin'ny fandalinana ny kaody ato amin'ity module ity dia hahita fahafahana bebe kokoa ianao hiara-miasa aminy. Mety ho tianao ny hanampy azy amin'ny kilasy, asa, fomba ary variables. Azonao atao foana ny mizara ny asanao ary mijery script hafa momba ny Check Point ao amin'ny fizarana CodeHub eo amin’ny fiaraha-monina Echéc et mat, izay mampiaraka ny mpamorona vokatra sy ny mpampiasa.

Faly coding ary misaotra namaky hatramin'ny farany!

Source: www.habr.com

Add a comment