Ho nolofatsa API ea Check Point ka Python SDK

Ho nolofatsa API ea Check Point ka Python SDKMatla a feletseng a ho sebelisana le li-API a senoloa ha a sebelisoa hammoho le khoutu ea lenaneo, ha ho khoneha ho hlahisa likopo tsa API le lisebelisoa tsa ho hlahloba likarabo tsa API. Leha ho le joalo, e ntse e sa bonahale Python Software Development Kit (eo ka mor'a moo e bitsoang Python SDK) bakeng sa Check Point Management API, empa ke lefeela. E nolofatsa haholo bophelo ba bahlahisi le ba chesehelang li-automation. Python e se e tumme haholo morao tjena mme ke nkile qeto ea ho tlatsa lekhalo le ho lekola likarolo tsa mantlha. Sheba Point Point API Python Development Kit. Sengoliloeng sena se sebetsa e le tlatsetso e ntle ho sengoloa se seng ka Habré Check Point R80.10 API. Tsamaiso ka CLI, mangolo le tse ling. Re tla sheba mokhoa oa ho ngola mangolo ka ho sebelisa Python SDK le ho shebisisa tšebetso e ncha ea Tsamaiso ea API ho mofuta oa 1.6 (e tšehetsoeng ho tloha ho R80.40). Ho utloisisa sengoloa, o tla hloka tsebo ea mantlha ea ho sebetsa le li-API le Python.

Check Point e nts'etsapele API ka mafolofolo mme hajoale tse latelang li lokollotsoe:

Python SDK hajoale e ts'ehetsa feela tšebelisano le Tsamaiso ea API le Gaia API. Re tla sheba lihlopha tsa bohlokoa ka ho fetisisa, mekhoa le mefuta-futa mojulung ona.

Ho nolofatsa API ea Check Point ka Python SDK

Ho kenya mojule

Module cpapi kenya kapele le ha bonolo ho tloha sebaka sa polokelo sa Check Point ho github ka thuso pip. Litaelo tse qaqileng tsa ho kenya li fumaneha ho README.md. Mojule ona o ikamahanya le maemo ho sebetsa le liphetolelo tsa Python 2.7 le 3.7. Sehloohong sena, mehlala e tla fanoa ho sebelisoa Python 3.7. Leha ho le joalo, Python SDK e ka tsamaisoa ka ho toba ho tswa ho Check Point Management Server (Smart Management), empa e tšehetsa Python 2.7 feela, kahoo karolo ea ho qetela e tla fana ka khoutu bakeng sa phetolelo ea 2.7. Hang ka mor'a ho kenya module, ke khothaletsa ho sheba mehlala ho li-directory mehlala_python2 и mehlala_python3.

Ho qala

E le hore re tsebe ho sebetsa le likarolo tsa mojule oa cpapi, re hloka ho kenya letsoho ho tsoa ho module cpapi bonyane lihlopha tse peli tse hlokahalang:

APIClient и APIClientArgs

from cpapi import APIClient, APIClientArgs

Sehlopha APIClientArgs e ikarabella bakeng sa liparamente tsa khokahano ho seva sa API, le sehlopha APIClient e ikarabella bakeng sa ho sebelisana le API.

Ho khetha li-parameter tsa khokahano

Ho hlalosa liparamente tse fapaneng tsa ho hokela API, o hloka ho etsa mohlala oa sehlopha APIClientArgs. Ha e le hantle, litekanyo tsa eona li hlalositsoe esale pele 'me ha li tsamaisa script ho seva sa taolo, ha li hloke ho boleloa.

client_args = APIClientArgs()

Empa ha o sebetsa ho moamoheli oa mokha oa boraro, o hloka ho hlakisa bonyane aterese ea IP kapa lebitso la moeti oa seva ea API (e tsejoang hape e le seva sa taolo). Mohlala o ka tlase, re hlalosa parameter ea khokahanyo ea seva mme re e fa aterese ea IP ea seva sa tsamaiso e le khoele.

client_args = APIClientArgs(server='192.168.47.241')

Ha re shebeng liparamente tsohle le boleng ba tsona ba kamehla bo ka sebelisoang ha o hokela ho seva sa API:

Likhang tsa __init__ mokhoa oa sehlopha sa 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

Ke lumela hore likhang tse ka sebelisoang maemong a sehlopha sa APIClientArgs li bonolo ho balaoli ba Check Point mme ha li hloke maikutlo a eketsehileng.

Ho hokela ka APIClient le mookameli oa litaba

Sehlopha APIClient Mokhoa o bonolo ka ho fetisisa oa ho e sebelisa ke ho sebelisa mookameli oa litaba. Sohle se hlokang ho fetisetsoa ho mohlala oa sehlopha sa APIClient ke li-parameter tsa khokahano tse hlalositsoeng mohatong o fetileng.

with APIClient(client_args) as client:

Motsamaisi oa litaba a ke ke a etsa mohala oa ho kena ho seva sa API ka bohona, empa o tla etsa mohala oa ho tsoa ha o tsoa. Haeba ka lebaka le itseng ho tsoa ha ho hlokahale kamora ho qeta ho sebetsa ka mehala ea API, o hloka ho qala ho sebetsa ntle le ho sebelisa mookameli oa litaba:

client = APIClient(clieng_args)

Teko ea khokahano

Tsela e bonolo ka ho fetisisa ea ho hlahloba hore na khokahanyo e kopana le litekanyetso tse boletsoeng ke ho sebelisa mokhoa check_fingerprint. Haeba netefatso ea palo ea sha1 hash bakeng sa menoana ea setifikeiti sa API ea seva e hloleha (mokhoa o khutlisitsoe ba bohata), hangata sena se bakoa ke mathata a khokahano mme re ka emisa ts'ebetso ea lenaneo (kapa ra fa mosebelisi monyetla oa ho lokisa data ea khokahano):

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

Ka kopo hlokomela hore nakong e tlang sehlopha APIClient e tla hlahloba mohala o mong le o mong oa API (mekhoa api_call и api_query, re tla bua ka bona ho feta hanyane) setifikeiti sa menoana sa sha1 ho seva sa API. Empa haeba, ha u hlahloba menoana ea sha1 ea setifikeiti sa seva sa API, phoso e fumanoa (setifikeiti ha se tsejoe kapa se fetotsoe), mokhoa ona check_fingerprint e tla fana ka monyetla oa ho eketsa / fetola tlhahisoleseling mabapi le eona mochining oa lehae ka bo eona. Cheke ena e ka emisoa ka botlalo (empa sena se ka khothaletsoa feela haeba mangolo a tsamaisoa ho seva ea API ka boyona, ha o hokela ho 127.0.0.1), ho sebelisoa khang ea APIClientArgs - safe_auto_accept (sheba haholoanyane ka APIClientArgs pejana ho "Defining parameters of connection").

client_args = APIClientArgs(unsafe_auto_accept=True)

Kena ho seva sa API

У APIClient ho na le mekhoa e ka bang 3 ea ho kena ka har'a seva sa API, 'me e' ngoe le e 'ngoe ea tsona e utloisisa moelelo sid(session-id), e sebelisoang ka bo eona pitsong e 'ngoe le e' ngoe e latelang ea API sehloohong (lebitso le hloohong ea paramethara ena ke X-chkp-sid), kahoo ha ho na tlhoko ea ho tsoela pele ho sebetsana le parameter ena.

mokhoa oa ho kena

Khetho e sebelisang ho kena le password (mohlala, lebitso la mosebelisi le password 1q2w3e li fetisitsoe joalo ka likhang tsa maemo):

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

Likarolo tse ling tsa boikhethelo li fumaneha hape ka mokhoa oa ho kena; mabitso a bona le litekanyetso tsa kamehla ke tsena:

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

Mokhoa oa ho kena_ka_api_key

Khetho ea ho sebelisa konopo ea api (e tšehelitsoeng ho qala ho mofuta oa tsamaiso R80.40/Management API v1.6, "3TsbPJ8ZKjaJGvFyoFqHFA==" ona ke boleng ba bohlokoa ba API bakeng sa e mong oa basebelisi ba seva sa taolo ka mokhoa oa tumello ea senotlolo sa API):

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

Ka mokhoa kena_ka_api_key mekhahlelo e tšoanang ea boikhethelo e fumaneha joalo ka mokhoa kena.

login_as_root mokhoa

Khetho ea ho kena mochining oa lehae ka seva ea API:

     login = client.login_as_root()

Ho na le li-parameter tse peli feela tse fumanehang bakeng sa mokhoa ona:

domain=None, payload=None

Mme qetellong API e ipitsa

Re na le likhetho tse peli tsa ho etsa mehala ea API ka mekhoa api_call и api_query. A re bone hore na phapang ke efe pakeng tsa bona.

api_call

Mokhoa ona o sebetsa bakeng sa mehala efe kapa efe. Re hloka ho fetisa karolo ea ho qetela bakeng sa pitso ea api le phallo ho sehlopha sa kopo ha ho hlokahala. Haeba moputso o se na letho, o ke ke oa fetisoa ho hang:

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

Sephetho sa kopo ena ka tlase ho sehiloeng:

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'})

Sephetho sa kopo ena ka tlase ho sehiloeng:

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

E-re ke behelle hang hang hore mokhoa ona o sebetsa feela bakeng sa mehala eo tlhahiso ea eona e kenyelletsang offset. Khopolo e joalo e etsahala ha e na le kapa e ka ba le tlhaiso-leseling e ngata. Ka mohlala, sena e ka 'na ea e-ba kopo ea lethathamo la lintho tsohle tse bōpiloeng tse amohelehang ho seva sa tsamaiso. Bakeng sa likopo tse joalo, API e khutlisa lethathamo la lintho tse 50 ka ho sa feleng (o ka eketsa moeli ho lintho tse 500 karabong). 'Me e le hore u se ke ua hula boitsebiso ka makhetlo a' maloa, ho fetola parameter ea offset ka kopo ea API, ho na le mokhoa oa api_query o etsang mosebetsi ona ka boomo. Mehlala ea mehala moo mokhoa ona o hlokahalang: mananeo a bonts'ang, baamoheli ba mananeo, marang-rang, likarete tsa ponts'o, lihlopha tsa li-show-adresses, li-show-gateways, show- simple-clusters, show-access- roles, show-trusted-clients, liphutheloana tsa pontšo. Ha e le hantle, re bona mantsoe a mangata ka lebitso la li-call tsena tsa API, kahoo li-call tsena li tla ba bonolo ho li tšoara api_query

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

Sephetho sa kopo ena ka tlase ho sehiloeng:

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
})

E sebetsana le liphetho tsa mehala ea API

Ka mor'a moo, o ka sebelisa mekhoa le mekhoa e meng ea phekolo APIResponse(ka bobeli ka hare ho mookameli oa moelelo le ka ntle). Ka tlelaseng APIResponse Mekhoa e 4 le mefuta e 5 e hlalositsoe esale pele; re tla lula ho tse bohlokoa ka ho fetesisa.

Ho nolofatsa API ea Check Point ka Python SDK

lebisang katlehong

Ho qala, e ka ba mohopolo o motle ho etsa bonnete ba hore mohala oa API o atlehile mme o khutlisitse sephetho. Ho na le mokhoa oa ho etsa sena lebisang katlehong:

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

E Khutlisa 'Nete haeba mohala oa API o atlehile (khoutu ea karabo - 200) le Bohata haeba e sa atleha (khoutu efe kapa efe ea karabo). Ho bonolo ho sebelisa hang kamora mohala oa API ho bonts'a tlhaiso-leseling e fapaneng ho latela khoutu ea karabelo.

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

boemo ba khoutu

E khutlisa khoutu ea karabo ka mor'a hore mohala oa API o etsoe.

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

Likhoutu tsa karabo tse ka bang teng: 200,400,401,403,404,409,500,501.

set_success_boemo

Tabeng ena, ho ka 'na ha hlokahala hore u fetole boleng ba boemo ba katleho. Ha e le hantle, u ka beha ntho leha e le efe moo, esita le khoele e tloaelehileng. Empa mohlala oa 'nete e ka ba ho khutlisetsa paramente ena ho False tlasa maemo a mang a tsamaeang le ona. Ka tlase, ela hloko mohlala ha ho na le mesebetsi e sebetsang ho seva sa tsamaiso, empa re tla nka kopo ena e sa atlehe (re tla beha katleho e fapaneng ho ba bohata, ho sa tsotellehe hore mohala oa API o atlehile mme o khutlisitse khoutu ea 200).

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

karabo()

Mokhoa oa karabelo o u lumella ho sheba bukantswe ka khoutu ya karabo (status_code) le mmele wa karabelo (mmele).

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']}}

ya data

E u lumella ho bona feela 'mele oa karabo ('mele) ntle le tlhahisoleseding e sa hlokahaleng.

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']}

phoso_molaetsa

Lintlha tsena li fumaneha feela ha phoso e etsahetse ha o ntse o sebetsa kopo ea API (khoutu ea karabelo ha 200). Sephetho sa mohlala

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

Mehlala e molemo

E latelang ke mehlala e sebelisang mehala ea API e kentsoeng ho Management API 1.6.

Pele, a re shebeng hore na mehala e sebetsa joang eketsa-moamoheli и eketsa-aterese-range. Ha re re re hloka ho theha liaterese tsohle tsa IP tsa subnet 192.168.0.0/24, octet ea ho qetela e 5, e le lintho tsa mofuta oa moamoheli, 'me u ngole liaterese tse ling tsohle tsa IP e le lintho tsa mofuta oa aterese. Tabeng ena, u ke ke ua kenyelletsa aterese ea subnet le aterese ea khaso.

Kahoo, ka tlase ke mongolo o rarollang bothata bona mme o theha lintho tse 50 tsa mofuta oa moamoheli le lintho tse 51 tsa mofuta oa aterese. Ho rarolla bothata, ho hlokahala mehala ea 101 API (ho sa baloe mohala oa ho qetela oa phatlalatso). Hape, ka ho sebelisa mojule oa nako, re bala nako eo e e nkang ho etsa sengoloa ho fihlela liphetoho li phatlalatsoa.

Ngola o sebelisa add-host le 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')

Sebakeng sa ka sa laboratoring, sengoloa sena se nka lipakeng tsa 30 le 50 metsotsoana ho e etsa, ho latela mojaro o ho seva sa taolo.

Joale ha re boneng mokhoa oa ho rarolla bothata bo tšoanang ka mohala oa API tlatsetso-sehlopha, tšehetso e ileng ea eketsoa ho API version 1.6. Pitso ena e u lumella ho etsa lintho tse ngata ka nako e le 'ngoe ka kopo e le' ngoe ea API. Ho feta moo, tsena e ka ba lintho tsa mefuta e fapaneng (mohlala, mabotho, li-subnet le libaka tsa liaterese). Kahoo, mosebetsi oa rona o ka rarolloa ka har'a moralo oa mohala o le mong oa API.

Sengoloa se sebelisang sehlopha sa li-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')

'Me ho tsamaisa sengoloa sena tikolohong ea lab ea ka ho nka metsotsoana e 3 ho isa ho e 7, ho latela mojaro o ho seva sa taolo. Ke hore, ka karolelano, linthong tse 101 tsa API, mohala oa mofuta oa batch o matha ka makhetlo a 10 ka potlako. Palong e kholoanyane ea lintho, phapang e tla ba e tsotehang le ho feta.

Joale a re boneng mokhoa oa ho sebetsa le set-objects-batch. Ka ho sebelisa mohala ona oa API, re ka fetola ka bongata paramethara efe kapa efe. A re ke re behe halofo ea pele ea liaterese ho tloha mohlaleng o fetileng (ho fihlela ho .124 mabotho, le mefuta e mengata) ho 'mala oa sienna,' me re fane ka 'mala oa khaki ho halofo ea bobeli ea liaterese.

Ho fetola 'mala oa lintho tse entsoeng mohlaleng o fetileng

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")

O ka hlakola lintho tse ngata ka mohala o le mong oa API o sebelisa hlakola-ntho-batch. Joale ha re shebeng mohlala oa khoutu o hlakolang mabotho ohle a entsoeng pejana ka tlatsetso-sehlopha.

Ho phumula dintho ka ho sebedisa 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)

Mesebetsi eohle e hlahang likhatisong tse ncha tsa software ea Check Point hang-hang e fumana mehala ea API. Kahoo, ho R80.40 "likarolo" tse joalo tse kang Revert to revision le Smart Task li ile tsa hlaha, 'me li-call tsa API tse tsamaellanang li ile tsa lokisetsoa hang-hang. Ho feta moo, ts'ebetso eohle ha o tloha ho li-consoles tsa Legacy ho ea ho Unified Policy e boetse e fumana tšehetso ea API. Ka mohlala, ntlafatso eo e leng khale e letetsoe ho mofuta oa software ea R80.40 e bile ho falla ha leano la Tlhahlobo ea HTTPS ho tloha ho mokhoa oa Lefa ho ea ho Mokhoa o Kopanetsoeng oa Pholisi, 'me ts'ebetso ena hang-hang e ile ea fumana mehala ea API. Mona ke mohlala oa khoutu e eketsang molao sebakeng se phahameng sa pholisi ea Tlhahlobo ea HTTPS e sa kenyelletseng lihlopha tsa 3 ho hlahloba (Bophelo, Lichelete, Litšebeletso tsa 'Muso), tse thibetsoeng ho hlahlojoa ho ea ka molao linaheng tse ngata.

Kenya molao ho leano la Tlhahlobo ea 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")

Ho tsamaisa mangolo a Python ho seva sa taolo ea Check Point

Tsohle di a tshwana README.md e na le tlhaiso-leseling ea ho tsamaisa mangolo a Python ka kotloloho ho tsoa ho seva sa taolo. Sena se ka ba bonolo ha o sa khone ho hokela seva sa API ho tsoa mochining o mong. Ke rekotile video ea metsotso e tšeletseng eo ho eona ke shebang ho kenya module cpapi le likarolo tsa ho tsamaisa mangolo a Python ho seva sa taolo. Mohlala, sengoloa se tsamaisoa se iketsetsang tlhophiso ea heke e ncha bakeng sa mosebetsi o joalo ka tlhahlobo ea marang-rang. Tshireletso CheckUp. Har'a likarolo tseo ke neng ke tlameha ho sebetsana le tsona: ts'ebetso ha e so hlahe ho Python 2.7 Kenyelletso, kahoo ho sebetsana le tlhahisoleseding eo mosebedisi a e kenyang, ho sebelisoa ts'ebetso kenyo_e tala. Ho seng joalo, khoutu e ts'oana le ea ho qala ho tsoa ho mechini e meng, feela ho bonolo ho e sebelisa kena_e le_motso, e le hore u se ke ua hlakisa lebitso la hau la mosebelisi, password le aterese ea IP ea seva sa taolo hape.

Script bakeng sa ho seta kapele ho Ts'ireletso ea Ts'ireletso

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()

Faele ea mohlala e nang le bukantswe ya phasewete extra_pass.conf
{
"passwords" : ["malware","malicious","infected","Infected"],
"phrases" : ["password","Password","Pass","pass","codigo","key","pwd","пароль","Пароль","Ключ","ключ","шифр","Шифр"] }

fihlela qeto e

Sehlooho sena se hlahloba feela menyetla ea motheo ea mosebetsi Python SDK le mojule cpapi(joalo ka ha u ka be u nahanne, ana ke li-synonymes), 'me ka ho ithuta khoutu e mojulung ona o tla fumana menyetla e mengata ea ho sebetsa le eona. Ho ka etsahala hore o tla batla ho e tlatsa ka lihlopha tsa hau, mesebetsi, mekhoa le mefuta-futa. U ka arolelana mosebetsi oa hau kamehla 'me u shebe mangolo a mang bakeng sa Check Point karolong eo CodeHub sechabeng CheckMates, e kopanyang bahlahisi ba lihlahisoa le basebelisi.

Thabela khouto mme re leboha ho bala ho fihlela qetellong!

Source: www.habr.com

Eketsa ka tlhaloso