### KLHST_WKS_HSDP_REASON Examples Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00012.html Specific examples of host status reason strings. ```text "1103/1.0.0.0/DBD500D3F6F04541910AD14C5CA47AE0" "1093/1.0.0.0/D2152D6328CE4328BCB3192632670E58" ``` -------------------------------- ### TryToInstallLicForSaas2 Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00573.html Installs the Administration Server license key. ```APIDOC ## TryToInstallLicForSaas2 ### Description Install the Administration Server license key. ### Parameters - **pKeyInfo** (params) - Required - License key information. - **bAsCurrent** (boolean) - Required - Specifies if the license should be installed as current. ``` -------------------------------- ### KLHST_APP_INFO Structure Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00499.html Example of the hierarchical structure for product information, including product IDs, versions, states, and state change timestamps. ```text +--- (PARAMS_T) +---KLHST_APP_INFO (PARAMS_T) +---1093 (PARAMS_T) | +---1.0.0.0 (PARAMS_T) | +---KLHST_APP_STATE = (INT_T)3 | +---KLHST_APP_STATE_TIME = (DATE_TIME_T)25-01-2018 09:10:27 +---1103 (PARAMS_T) | +---1.0.0.0 (PARAMS_T) | +---KLHST_APP_STATE = (INT_T)3 | +---KLHST_APP_STATE_TIME = (DATE_TIME_T)25-01-2018 09:10:27 +---ConnProd (PARAMS_T) +---1.0.0.0 (PARAMS_T) +---KLHST_APP_STATE = (INT_T)3 +---KLHST_APP_STATE_TIME = (DATE_TIME_T)25-01-2018 09:10:27 ``` -------------------------------- ### LicenseKeys::SaasTryToInstall Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00574_af67ac6ced311efd847c6f0f078853b87.html Installs an administration server's license. This method allows for installing a license either as the active license or as a reserved license. ```APIDOC ## SaasTryToInstall ### Description Installs an administration server's license. The license must be placed in the license store before calling this method. ### Parameters - **pInData** (params) - Required - Input data container. Must contain "KLLIC_SERIAL" (paramString) representing the serial number of the license. - **bAsCurrent** (boolean) - Required - If true, the license is installed as the active one; if false, it is installed as a reserved one. ### Exceptions - Throws an exception in case of error. ``` -------------------------------- ### Install License Key Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00574_a42d0b5d83d540627d8cfe770f514c2d5.html Attempts to install a license key using an activation code, with fallback logic to download and install key files if specific server errors occur. ```python try: wstrSerial = oLicenseKeys.InstallKey(KlAkOAPI.Params.KlAkParams({"KLLICSRV_KEYDATA": {"KLLIC_LICFILE": wstrActivationCode.encode('ascii'), "KLLIC_IFKEYFILE": False} })).RetVal() except KlAkOAPI.Error.KlAkError as err: if err.code == 2351 and (err.subcode == 3 or err.subcode == 34): # code KLOLA::KLOLA_ERR_SERVER (2351), subcode KLOLAEL_ERR_SERVER_1_REQUIRED (3) or KLOLAEL_ERR_LICENSE_NOT_FOUND (34) arrKeys = oLicenseKeys.DownloadKeyFiles(wstrActivationCode).RetVal() for arrKey in arrKeys: oLicenseKeys.InstallKey(KlAkOAPI.Params.KlAkParams({"KLLICSRV_KEYDATA": {"KLLIC_LICFILE": arrKey, "KLLIC_IFKEYFILE": False} })) else: raise ``` -------------------------------- ### LicenseInfoSync::TryToInstallLicForSaas2 Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00573_a4f030d9057b9b25332124aac49943c06.html Installs the Administration Server license key. This method allows specifying whether the key should be installed as the active license or as a reserved license. ```APIDOC ## LicenseInfoSync::TryToInstallLicForSaas2 ### Description Installs the Administration Server license key. This method allows specifying whether the key should be installed as the active license or as a reserved license. ### Parameters - **pKeyInfo** (params) - Required - License key property container. See List of license key properties for the names of the properties. - **bAsCurrent** (boolean) - Required - true if it is necessary to install a license key as an active one; false if it is necessary to install the license key as a reserved one. ### Exceptions - Throws exception in case of error. ``` -------------------------------- ### TryToInstallLicForSaas2() Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/functions_0x74.html Attempts to install a license for SaaS 2.0. ```APIDOC ## TryToInstallLicForSaas2() ### Description Attempts to install a license for the SaaS 2.0 environment. ### Returns - **LicenseInfoSync** - The synchronization information for the license. ``` -------------------------------- ### Standalone Installation Package Attributes Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00318.html List of supported attributes for configuring standalone installation packages. ```APIDOC ## Standalone Installation Package Attributes ### Description Attributes used to define the configuration for standalone installation packages within the Kaspersky Security Center. ### Parameters | Attribute | Type | Description | |---|---|---| | KLPKG_evpPkgPath | paramString | Executable file (standalone package) path relative to folder set in "ExternalPkgFolder" parameter of Kaspersky Administration Server settings. | | KLPKG_EXT_LOC_STRINGS | paramParams | External localization strings (optional). | | UseProxy | paramBool | Use proxy (optional). | | ProxyServerAddress | paramString | Proxy address (optional). Format: ":". Special value "*autodetect*" means autodetect proxy settings (only for cloud solutions). | | ProxyServerUser | paramString | Proxy user (optional). | | ProxyServerPassword | paramBinary | Encrypted proxy password (optional). | ``` -------------------------------- ### POST /api/v1.0/Session.StartSession Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00501.html Starts a session on a target secondary server. ```APIDOC ## POST /api/v1.0/Session.StartSession ### Description Starts a session on a target secondary server using a hybrid session identifier. ### Method POST ### Endpoint https://localhost:13299/api/v1.0/Session.StartSession ### Response #### Success Response (200) - **PxgRetVal** (string) - The identifier of the created session. ``` -------------------------------- ### Certificate Parameter Structure Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00403.html Example showing the hierarchical structure of certificate parameters including extensions, issuer, public key, and validity information. ```text +--- (paramParams) +---CertExtensions = (paramString)": X509v3 Basic Constraints: critical CA:TRUE X509v3 Key Usage: Digital Signature, Key Encipherment, Certificate Sign, CRL Sign X509v3 Subject Alternative Name: DNS:server1.example.com, DNS:mail.example.com, DNS:www.example.com" +---CertIssuer = (\ref kloapi_type_paramString)"commonName = MyCommonName emailAddress = MyEmail@mail.com" +---CertPublicKey = (\ref kloapi_type_paramString)"Public-Key: (1024 bit) Modulus: 00:d9:43:99:65:2d:28:67:4a:e3:97:2f:15:1b:ac: 48:57:07:59:f5:b8:81:e9:6b:74:91:43:a8:0b:90: b7:8f:e4:83:04:02:a2:df:33:dc:f2:ad:75:21:a8: 71:dc:0f:b5:5e:72:78:0b:90:5f:b1:1b:f6:0c:61: eb:76:7f:e0:cc:ba:61:cf:eb:ee:35:41:24:68:17: 49:b4:ea:ff:0a:d6:11:65:20:e8:60:d9:22:65:c1: 1f:af:a0:80:b3:3c:a6:64:3a:24:94:1a:5e:ec:b0: de:11:45:08:ab:be:a9:b4:90:2a:94:50:6e:ca:7d: 3d:fd:d7:00:12:6c:ef:29:3f Exponent: 65537 (0x10001)" +---CertSerial = (\ref kloapi_type_paramString)"089E083D1A39DD08F1FF892C4F0D32CC" +---CertSigAlgo = (\ref kloapi_type_paramString)"sha1WithRSAEncryption" +---CertSignature = (\ref kloapi_type_paramString)"Signature Algorithm: sha1WithRSAEncryption b4:81:57:66:4a:84:01:6f:ae:15:2d:3e:f8:a1:d1:b6:ad:e1: 13:e2:3a:cd:7e:9c:48:d1:df:3e:c5:73:8a:2a:14:86:f1:e4: 9e:f6:83:f9:45:fe:39:9b:0e:7b:db:bc:53:59:ef:ae:03:b2: 48:c6:84:1e:de:83:39:78:43:a1:32:57:32:05:9a:dd:2d:0b: 5d:6e:ef:ce:86:06:c3:53:12:d3:27:fc:ee:14:2f:55:89:bc: e1:ac:c0:21:de:0f:c5:78:73:91:bb:37:9b:4b:2d:57:e9:27: 37:af:d8:e6:97:bb:20:ec:cd:05:b6:fe:43:ba:a1:49:a8:09: ad:ae" +---CertSubject = (\ref kloapi_type_paramString)"commonName = MyCommonName emailAddress = MyEmail@mail.com" +---CertSubjectAltNames = (\ref kloapi_type_paramString)"DNS:server1.example.com DNS:mail.example.com DNS:www.example.com" +---CertValidFrom = (\ref kloapi_type_paramString)"May 19 19:49:35 2017 GMT" +---CertValidTo = (\ref kloapi_type_paramString)"Sep 16 19:49:35 2017 GMT" +---CertVersion = (paramInt)3 ``` -------------------------------- ### ApprovePatch Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00522.html Gives approval to a specific patch to start the installation process. ```APIDOC ## ApprovePatch ### Description Approves a patch for installation using its unique identifier. ### Parameters - **szwPatchId** (wstring) - Required - The unique identifier of the patch. - **parOptions** (params) - Required - Additional options for the approval process. ### Returns - **params** - The result of the approval operation. ``` -------------------------------- ### Execute Sample Script Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00466.html Runs a sample script to verify the installation and connectivity. ```bash >.\samples\sample_connect.py ``` -------------------------------- ### Requesting Dashboard Statistics Data Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00048.html Example structure for requesting specific dashboard data using KLPPT_DASHBOARD with unique GUIDs for each dashboard type. ```text +--- (paramParams) +---KLPPT_DASHBOARD (paramParams) +---4574FED1-ECC9-4f60-83D1-5BF5B84EB897 (paramParams) | +---KLRPT_DSH_TYPE = (paramInt)20 | +---id = (paramInt)0 | +---bIncludeVS = (paramBool)1 +---92A6E519-BF61-4902-B87D-A526FEFB91AA (paramParams) +---KLRPT_DSH_TYPE = (paramInt)2 +---KLPPT_StatFinishTime = (paramDateTime)23-03-2017 12:23:45 +---KLPPT_StatPeriodInSec = (paramInt)604800 +---id = (paramInt)-1 +---KLRPT_QUERY_ID = (paramInt)12 ``` -------------------------------- ### Main Execution Flow for User and Device Setup Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00465.html Orchestrates the connection, user creation, and asynchronous enrollment process. ```python def main(): """ This sample shows how you can add internal user and create an Android installation package""" print (main.__doc__) #connect to KSC server using basic auth by default server = GetServer() oUserDevicesApi = KlAkUserDevicesApi(server) oDataProtectionApi = KlAkDataProtectionApi(server) bPasswordProtected = oDataProtectionApi.ProtectUtf16StringGlobally("test1234!").RetVal() # add users oUsers = KlAkSecurityPolicy(server) users = [] for i in range(5): strUserName = f"User_{i}_{dateTimeToStr(datetime.datetime.now()).replace('-', '_').replace(':', '_')}" nUserID = oUsers.AddUser({"KLSPL_USER_NAME": strUserName, "KLSPL_USER_FULL_NAME": strUserName, "KLSPL_USER_PWD_ENCRYPTED": paramBinary( (bPasswordProtected))}).RetVal() print ('Added user', strUserName, ', id =', nUserID) user = User(strUserName, nUserID, f"{strUserName}@example.com") users.append(user) asyncio.run(enrollUsers(users, oUserDevicesApi)) if __name__ == '__main__': main() ``` -------------------------------- ### Policy::ExportPolicy2 Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00597_ac18f0aa2aebe93846e1bd5af8c5b6f00.html Starts a policy export process. The method returns a URL that can be used to download the policy settings file via an HTTP GET request. ```APIDOC ## Policy::ExportPolicy2 ### Description Starts policy export using HTTP GET. Use the returned value as a URL to download the policy settings file from the server using the HTTP GET method. The time interval between each request to the server must not exceed 5 minutes. ### Parameters #### Path Parameters - **lPolicy** (int) - Required - The unique identifier of the policy to export. ### Response - **Returns** (string) - A URL string used to perform an HTTP GET request to download the policy file. ``` -------------------------------- ### Main Execution Flow Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00459.html Demonstrates the workflow of connecting, finding a task, and running it. ```python def main(): """ This sample shows how you can find and execute task """ print (main.__doc__) #connect to KSC server using basic auth by default server = GetServer() oHostGroup = KlAkHostGroup(server) nRootGroupId = oHostGroup.GroupIdGroups().RetVal() oTasks = KlAkTasks(server) strInterestingTaskName = 'TestTask' strFoundTask = FindTask(oTasks, strInterestingTaskName) if strFoundTask == None or strFoundTask == '': print('Task', strInterestingTaskName, 'not found') else: nResult = RunTaskAndReturnResult(server, oTasks, strFoundTask) if 4 == nResult: print('Task result is Success') else: print('Task result is Failure') if __name__ == '__main__': main() ``` -------------------------------- ### Define HostList for Task Scope Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00031.html Example structure for defining a list of target hosts using either HostName or HostDispName, including optional preliminary start flags. ```text +---0 (paramParams) +---HostName = (paramString)"295ce3ac-f4b7-47e9-a7a5-b6aa7cb74e66" +---1 (paramParams) +---HostName = (paramString)"638168dc-735d-40af-88a5-b2f28eea6e99" +---2 (paramParams) +---HostDispName = (paramString)"Host3" +---Preliminary = (paramBool)true +---3 (paramParams) +---HostDispName = (paramString)"Host4" +---Preliminary = (paramBool)false ``` -------------------------------- ### Initialize Server Connection Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00604_a0fbb2baf621cd7d106aa4b71556638f0.html Establishes a connection to the Administration Server. ```python server = KlAkOAPI.AdmServer.KlAkAdmServer.Create("https://ksc.example.com:13299", "username", "password") ``` -------------------------------- ### Initialize HostMoveRules Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00555.html Establishes a connection to the Administration Server and initializes the HostMoveRules object. ```python server = KlAkOAPI.AdmServer.KlAkAdmServer.Create("https://ksc.example.com:13299", "username", "password", verify = False) oHostMoveRules = KlAkOAPI.HostMoveRules.KlAkHostMoveRules(server) ``` -------------------------------- ### UTC Time Format Examples Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00002.html Examples of absolute and relative UTC time formats. ```text T"2005-04-27 23:59:01" ``` ```text CURTIME([]) ``` -------------------------------- ### Check Product State Operation Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00587_a1460659ccda9d76b0228071d2cf373fb.html Example showing how to initiate a product state change and poll for its completion using the returned request ID. ```cpp strRequestId = SetProductStateAsync; pResParams = CheckActionState(strRequestId); bIsRunning = pResParams.Get("Products").Get(ProductId).Get("ProductRunning"); ``` -------------------------------- ### Main Execution Entry Point Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00461.html Initializes the server connection and triggers license validation for the main server and virtual servers. ```python def main(): """ This sample shows how you can see licenses in use """ print (main.__doc__) #connect to KSC server using basic auth by default server = KlAkAdmServer.Create(server_url, username, password, verify = SSLVerifyCert) print('Main server licenses:') if not FindActiveLicense(server): print('FAILURE! There''s no active license on server') EnumVServersAndTheirLicenses(server) if __name__ == '__main__': main() ``` -------------------------------- ### Install KlAkOAPI Package Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00466.html Installs the KlAkOAPI package and its dependencies from the provided tar.gz archive. ```bash >pip install KlAkOAPI-1.0.0.0.tar.gz ``` -------------------------------- ### Initialize HostMoveRules in Python Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00555_a5218b0a8b70524f0d885e699c074ec2d.html Establishes a connection to the Administration Server and initializes the HostMoveRules object using the KlAkOAPI package. ```python server = KlAkOAPI.AdmServer.KlAkAdmServer.Create("https://ksc.example.com:13299", "username", "password", verify = False) oHostMoveRules = KlAkOAPI.HostMoveRules.KlAkHostMoveRules(server) ``` -------------------------------- ### Binary Value Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00002.html Example of a binary value provided in hex format with the 0x prefix. ```text 0xF41748C0BEF943a6AE2C5D1010F046AD ``` -------------------------------- ### AKPatches::ApprovePatch Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00522_a9b3f7d90948ff134b1a650876148dea6.html Approves a patch for installation. This is required for patches that cannot be installed without administrator approval. ```APIDOC ## AKPatches::ApprovePatch ### Description Give approval to the patch on start installation. This command is applicable to patches which have no right to be installed without approval of the administrator. ### Parameters - **szwPatchId** (wstring) - Required - The patch identifier (see KLSTS_Par_PatchId). - **parOptions** (params) - Required - Object containing additional parameters: - **NeedBackupServer** (boolean) - Optional - true if it is required to do SC-server backup before installation of the patch. ### Response - **ppResult** (params) - Contains the following attributes: - **CallResult** (boolean) - true if success. - **ErrorDescription** (wstring) - Error description, empty if no error. ``` -------------------------------- ### Task Parameters Configuration Sample Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00273.html Example structure of task parameters including update source list, retranslation schema, and directory settings. ```text +--- (paramParams) ... +---TASK_ADDITIONAL_PARAMS (paramParams) ... | +---KLSRV_FORCE_UPD_SLAVES = (paramBool)false ... | +---UpdateSourceList (paramArray) | | +---0 (paramParams) | | +---type = (paramInt)3 | | +---url = (paramString)"\\test_host\share" | | +---use_proxy = (paramBool)true ... | +---retranslation_schema = (paramInt)1 ... | +---use_additional_targets = (paramBool)false ... | +---retranslation_dir = (paramString)"C:\ProgramData\KasperskyLab\adminkit\1093\.working\share\Updates" ... | +---SharePassword = paramBinary (size = 184): 474C4F42158E40138000000036619C1327EF629B7EDA2CF08... | +---ShareUsername = (paramString)"test_login" ... | +---additional_targets (paramArray) | | +---0 = (paramString)"D:\test_share\" ``` -------------------------------- ### Create an administration group using KlAkOAPI Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00554_a7f52d6b70986751de7453a1daa7308e0.html Demonstrates initializing the administration server and creating a new group under the root group using the KlAkOAPI Python package. ```python server = KlAkOAPI.AdmServer.KlAkAdmServer.Create("https://ksc.example.com:13299", "username", "password", verify = False) oHostGroup = KlAkOAPI.HostGroup.KlAkHostGroup(server) nRootGroupId = oHostGroup.GroupIdGroups().RetVal() nNewGroupId = oHostGroup.AddGroup({'name': 'Test group', 'parentId': nRootGroupId}).RetVal() ``` -------------------------------- ### HTTP Request Headers Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/index.html Example of the required HTTP headers for a KSC Open API request. ```http POST /api/v1.0/TestInterface.ScMethod1 HTTP/1.1 Content-Type: application/json Content-Length: 56 Accept-Encoding: gzip, deflate ``` -------------------------------- ### HostGroup::GetHostProducts Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00554_a3462eed9c19e7c832333a09301a044aa.html Retrieves a list of installed products, including their versions and installation details, for a specified host. ```APIDOC ## HostGroup::GetHostProducts ### Description Returns information about installed products on the host. ### Parameters - **_strHostName_** (wstring) - Required - Host name (GUID-like ID). ### Response - **Product** (paramParams) - Container with product names and versions. - **Version** (paramParams) - Container with version details: - **InstallTime** - **InstallationId** - **DisplayName** - **BaseRecords** - **ConnDisplayName** - **ConnProdVersion** - **ConnectorComponentName** ``` -------------------------------- ### Initialize Administration Server Connection Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00574_a42d0b5d83d540627d8cfe770f514c2d5.html Establishes a connection to the KSC Administration Server and initializes the LicenseKeys object. ```python server = KlAkOAPI.AdmServer.KlAkAdmServer.Create("https://ksc.example.com:13299", "username", "password", verify = False) oLicenseKeys = KlAkOAPI.LicenseKeys.KlAkLicenseKeys(server) ``` -------------------------------- ### KSC API Data Type Examples Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/index.html Examples of JSON representations for various KSC API parameter types. ```json "Some text with \"double quotes\" must be like this." ``` ```json 1234 ``` ```json {"type": "long", "value": 13} ``` ```json {"type": "datetime", "value": "2016-09-19T15:22:35Z"} ``` ```json {"type": "date", "value": "2016-09-19"} ``` ```json {"type": "binary", "value": "c29tZXRleHQ="} ``` ```json {"type": "float", "value": 1.23} ``` ```json {"type": "double", "value": 1.23} ``` ```json [{"type": "date", "value": "2016-09-19"}, {"type": "datetime", "value": "2016-09-19T15:22:35Z"}] ``` ```json {"type": "params", "value": {"var1": 23, "var2": "str12", "var3": {"type": "date", "value": "2016-09-19"}}} ``` -------------------------------- ### Main Execution Entry Point Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00452.html Parses command line arguments and initiates the KSC connection and file download process. ```python def main(): """ Depending on command line arguments this module shows KSC connection with different authentication methods. Address of KSC server is optional argument, and if not stated then current machine FQDN is used (supposed tests are run on machine where KSC server is installed) Samples of usage: >> python.exe sample_nlst.py -nlstfileid=-1234 -downloadpath c:/work/dump/ -nlstname TEST_KLAKAUT_NETWORK_LIST "" #argument parsing parser = argparse.ArgumentParser(description='This module provides samples of KSC authorization') group_auth_type = parser.add_mutually_exclusive_group(required=False) AddServerAddressArgs(parser) args = parser.parse_args() #KSC connection server = Connect(args.serveraddress, args.port, args.user, args.password, args.hostaddress) DownloadNlstFile(server, args.nlstname, args.nlstfileid, args.downloadpath) if __name__ == '__main__': main() ``` -------------------------------- ### JSON Response Object Examples Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/index.html Examples of JSON objects returned in the response body for successful method execution. ```json { "PxgRetVal": 15, "OutVar1": "value1", "OutVar2": "value2" } ``` ```json { "PxgRetVal": "abc" } ``` ```json { } ``` -------------------------------- ### JSON Request Body Examples Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/index.html Examples of JSON objects used in the HTTP request body for method parameters. ```json { "arg1":"value1" } ``` ```json { "arg1":"value2", "arg2":43 } ``` ```json { } ``` -------------------------------- ### Initialize Administration Server Connection Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00524_a2b34b13591edd83987e08009017e5813.html Establishes a connection to the Kaspersky Security Center Administration Server. ```python server = KlAkOAPI.AdmServer.KlAkAdmServer.Create("https://ksc.example.com:13299", "username", "password", verify = False) ``` -------------------------------- ### KLOAPI Array JSON Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00435.html Example of a JSON array containing date and datetime objects as used in KLOAPI. ```json [{"type": "date", "value": "2016-09-19"}, {"type": "datetime", "value": "2016-09-19T15:22:35Z"}] ``` -------------------------------- ### Logical Expression Structure Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00105.html Example of a nested logical expression structure using LOP and COP constants. ```text +--- +---ARGS | +---0 | | +---OP = KLLX_COP_EQ | | +---name = "strAttr1" | | +---val = "val1" | +---1 | | +---OP = KLLX_COP_L | | +---name = "nAttr2" | | +---val = 100 | +---2 | +---ARGS | | +---0 | | | +---OP = KLLX_COP_EX | | | +---name = "nAttr3" | | +---1 | | +---OP = KLLX_COP_NEQ | | +---another = "nAttr5" | | +---name = "nAttr4" | +---LOP = KLLX_LOP_OR +---LOP = KLLX_LOP_AND ``` -------------------------------- ### Task Start Condition Constants Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00031.html Constants used to define task start conditions within the KSC API. ```text +--- "KLPRTS_START_CONDITION_TYPE" = 3 +--- "KLPRTS_START_CONDITION_VALUE_EX" - See Task states +--- "KLPRTS_START_CONDITION_VALUE" - Group task ID +--- "KLPRTS_START_CONDITION_VALUE2" - Task ID in KLPRTS::TasksStorage ``` -------------------------------- ### AKPatches::ForbidPatch Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00522_aea57820625dd1ec427cc67fb7ff651d4.html Forbids the installation of a patch. Once forbidden, the system will no longer send notifications regarding the approval of this patch for installation. ```APIDOC ## AKPatches::ForbidPatch ### Description Forbid installation of the patch. After this is called, there will be no more notifications that this patch is expecting approval for installation. ### Parameters - **szwPatchId** (wstring) - Required - The patch identifier (see KLSTS_Par_PatchId). - **parOptions** (params) - Required - Reserved parameters. ### Response - **ppResult** (params) - Contains the following attributes: - **CallResult** (boolean) - true if success. - **ErrorDescription** (wstring) - Error description, empty if no error. ``` -------------------------------- ### Initialize KlAkOAPI Gateway Connection Script Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00452.html This script demonstrates the initial setup and imports required to use the KlAkOAPI package for gateway connections. It includes default credential configurations for authentication. ```python # #!/usr/bin/python -tt # -*- coding: utf-8 -*- """This module presents samples of usage KlAk package to download network list files via gateway connection to the specified host""" import sys import os import argparse import socket import getpass from urllib.parse import urlparse from KlAkOAPI.Params import KlAkParams, KlAkArray, paramParams, strToBin from KlAkOAPI.AdmServer import KlAkAdmServer from KlAkOAPI.Error import KlAkError, KlAkResponseError from KlAkOAPI.CgwHelper import KlAkCgwHelper from KlAkOAPI.GatewayConnection import KlAkGatewayConnection from KlAkOAPI.HostGroup import KlAkHostGroup from KlAkOAPI.ChunkAccessor import KlAkChunkAccessor from KlAkOAPI.NagNetworkListApi import KlAkNagNetworkListApi # For basic auth connection you should either state '-user' and '-password' arguments or the following credentials are applied: KSCServerUserAccountDefault / KSCServerUserPasswordDefault # You should create internal user with these credentials in advance on KSC using WC or MMC console and grant it certain privileges, such as 'Main Administrator' role # For Windows platform NTLM auth is applied when user and password arguments are omitted KSCServerUserAccountDefault = 'klakoapi_test' KSCServerUserPasswordDefault = 'test1234!' # If the '-password' parameter is not defined for connecting to the server, an attempt will be made to read the value of this parameter from the KSCServerUserPasswordEnv environment variable KSCServerUserPasswordEnv = 'KLOAPI_USER_PASSWORD' ``` -------------------------------- ### KlAkAdmServer.Create Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00466.html Establishes a connection to the Administration Server using username and password authentication. ```APIDOC ## KlAkAdmServer.Create ### Description Creates a connection to the Administration Server using credentials. ### Signature `KlAkOAPI.AdmServer.KlAkAdmServer.Create(server_url, username, password, verify = False, vserver = 'vs1')` ### Parameters - **server_url** (string) - The address of the Administration Server (e.g., https://machine.domain:13299). - **username** (string) - The account username. - **password** (string) - The account password. - **verify** (string/boolean) - Path to the SSL certificate or False for unverified connection. - **vserver** (string) - The name of the virtual server to connect to. ``` -------------------------------- ### EnumAllKeys Return Value Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00596_a20aa02fb4bcdf549098d786ca54d6e2b.html Example of the array structure returned by the EnumAllKeys method, showing a list of key name strings. ```text (ARRAY_T) +---0 = (STRING_T)"Key_0" +---1 = (STRING_T)"Key_10" +---2 = (STRING_T)"Key_12" +---3 = (STRING_T)"Key_14" +---4 = (STRING_T)"Key_2" +---5 = (STRING_T)"Key_4" +---6 = (STRING_T)"Key_6" +---7 = (STRING_T)"Key_8" ``` -------------------------------- ### Main Execution Logic Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00455.html Connects to the KSC server, resolves the host, starts the specified task, and waits for completion. ```python def main(): """ Starts host task and waits its completion. Samples of usage: >> python.exe sample_run_host_task.py -task "Task to execute" """ #argument parsing parser = argparse.ArgumentParser(description='This module provides samples of execution of host\'s task') group_auth_type = parser.add_mutually_exclusive_group(required=False) AddArgs(parser) args = parser.parse_args() server_address = socket.getfqdn() server_port = 13299 server_url = 'https://' + server_address + ':' + str(server_port) #KSC connection server = GetServer(server_url) hostaddress = args.hostaddress if hostaddress is None: hostaddress = socket.getfqdn() hostId = GetHostNameByHostFQDN(server, hostaddress) pTaskData = FindHostTask(server, hostId, args.task) taskTsId = pTaskData['TASK_UNIQUE_ID'] strProductName = pTaskData['TASKID_PRODUCT_NAME'] strProductVersion = pTaskData['TASKID_VERSION'] nagent = CreteGatewayToHost(server, server_url, hostId) nagHstCtl = KlAkNagHstCtl(nagent) StartHostTask(nagHstCtl, taskTsId, strProductName, strProductVersion) WaitTaskCompletion(nagHstCtl, taskTsId, strProductName, strProductVersion) if __name__ == '__main__': main() ``` -------------------------------- ### KLLIC_APP_IDS Structure Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00122.html Example showing the hierarchical structure of KLLIC_APP_IDS containing application IDs and their associated licensed object counts. ```text +--- (PARAMS_T) ... +---KLLIC_APP_IDS (PARAMS_T) | +---1017 (PARAMS_T) | | +---KLLIC_APP_ID = (INT_T)1017 | | +---KLLIC_LICOBJECT_66 = (INT_T)5 | +---1750 (PARAMS_T) | +---KLLIC_APP_ID = (INT_T)1750 | +---KLLIC_LICOBJECT_1 = (INT_T)50 | +---KLLIC_LICOBJECT_102 = (INT_T)-1 | +---KLLIC_LICOBJECT_54 = (INT_T)-1 | +---KLLIC_LICOBJECT_58 = (INT_T)-1 | +---KLLIC_LICOBJECT_60 = (INT_T)-1 | +---KLLIC_LICOBJECT_68 = (INT_T)-1 | +---KLLIC_LICOBJECT_70 = (INT_T)-1 | +---KLLIC_LICOBJECT_72 = (INT_T)-1 ... ``` -------------------------------- ### Configure Chart Parameters Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00604_a0fbb2baf621cd7d106aa4b71556638f0.html Sets up the chart data and visual configuration. ```python if hostsUUID in pDashboards: # compose parameters with the statistics data for a chart hostsDash = pDashboards[hostsUUID] parChartData = KlAkOAPI.Params.KlAkParams({'data': [hostsDash.GetValue('nOkCount'), hostsDash.GetValue('nWrnCount'), hostsDash.GetValue('nCrtCount')], 'name': hostsUUID}) parChartInfo = KlAkOAPI.Params.KlAkParams({}) parChartInfo.AddArray('KLRPT_CHART_DATA', [parChartData]) parChartInfo.AddString('KLRPT_CHART_DATA_DESC', 'Current state of the most anti-virus protection ') parChartInfo.AddString('KLRPT_CHART_LGND_DESC', 'number of hosts with:') parChartInfo.AddArray('KLRPT_CHART_SERIES', ['Ok protection status', 'Warning protection status', 'Critical protection status']) parChartInfo.AddBool('KLRPT_CHART_PIE', True) ``` -------------------------------- ### Initialize KlAkOAPI Connection Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00455.html Basic setup and imports for the KlAkOAPI package. Requires pre-configured internal user credentials on the Administration Server. ```python # #!/usr/bin/python -tt # -*- coding: utf-8 -*- """This module presents sample of usage KlAkOAPI package to perform task on host """ import sys import os import argparse import socket import time import getpass from sys import platform from urllib.parse import urlparse from KlAkOAPI.Params import KlAkParams, KlAkArray, paramParams, strToBin from KlAkOAPI.AdmServer import KlAkAdmServer from KlAkOAPI.Error import KlAkError, KlAkResponseError from KlAkOAPI.CgwHelper import KlAkCgwHelper from KlAkOAPI.GatewayConnection import KlAkGatewayConnection from KlAkOAPI.HostGroup import KlAkHostGroup from KlAkOAPI.ChunkAccessor import KlAkChunkAccessor from KlAkOAPI.Tasks import KlAkTasks from KlAkOAPI.HostTasks import KlAkHostTasks from KlAkOAPI.NagHstCtl import KlAkNagHstCtl # For basic auth connection you should either state '-user' and '-password' arguments or the following credentials are applied: KSCServerUserAccountDefault / KSCServerUserPasswordDefault # You should create internal user with these credentials in advance on KSC using WC or MMC console and grant it certain privileges, such as 'Main Administrator' role # For Windows platform NTLM auth is applied when user and password arguments are omitted KSCServerUserAccountDefault = 'klakoapi_test' KSCServerUserPasswordDefault = 'test1234!' ``` -------------------------------- ### Computer Query Parameter Structure Example Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00279.html Example structure of a computer query showing nested subcontainers and their respective query strings and parameters. ```text +--- (paramParams) +---Name = (paramString)"My Computer Query" +---ORedArray (paramArray) | +---0 (paramParams) | +---Name = (paramString)"Query Part 1" | +---AVBasesPageSettings (paramParams) - AV Bases subcontainer | | +---Query = (paramString)"(&(&(KLHST_WKS_AV_BASES_DATE>=T"2017-8-3 12:57:47")(KLHST_WKS_AV_BASES_DATE<=T"2017-8-3 13:57:47")) | | | (&(KLHST_WKS_AV_BASES_RECORDS>=1)(KLHST_WKS_AV_BASES_RECORDS<=2000000000)) | | | (&(KLHST_WKS_LAST_FULLSCAN>=T"2017-8-3 13:57:47")(KLHST_WKS_LAST_FULLSCAN<=T"2017-8-3 14:57:47")) | | | (&(KLHST_WKS_VIRUS_COUNT>=1)(KLHST_WKS_VIRUS_COUNT<=1000000)))" | | +---avb_records_from = (\ref kloapi_type_paramInt)1 - AV Bases records range (from). See \ref ak_hst_attributes_srchonly "KLHST_WKS_AV_BASES_RECORDS" | | +---avb_records_to = (paramInt)2000000000 - AV Bases records range (to) | | +---avbases_from = (paramDateTime)03-08-2017 12:57:00 - AV Bases date (from). See KLHST_WKS_AV_BASES_DATE | | +---avbases_to = (paramDateTime)03-08-2017 13:57:00 - AV Bases date (to) | | +---avbases_days = (paramInt)3 - AV Bases date in form of "days past for now". If it != 0 then avbases_from and avbases_to ignored. See KLHST_WKS_AV_BASES_DATE | | +---lfs_from = (paramDateTime)03-08-2017 13:57:00 - Last full scan time (from). See KLHST_WKS_LAST_FULLSCAN | | +---lfs_to = (paramDateTime)03-08-2017 14:57:00 - Last full scan time (to) | | +---lfs_days = (paramInt)3 - Last full scan time in form of "days past for now". If lfs_days != 0 then lfs_from and lfs_to ignored. See KLHST_WKS_LAST_FULLSCAN | | +---viruses_from = (paramInt)1 - Viruses found (form). See KLHST_WKS_LAST_FULLSCAN | | +---viruses_to = (paramInt)1000000 - Viruses found (to) | +---AdPageSettings (paramParams) - ActiveDirectory subcontainer | | +---ActiveDirOUGroupID = (paramInt)432 - Active Directory organizational unit ID. See KLHST_AD_ORGUNIT | | +---SearchInSubDir = (paramBool)true - Search in nested organizational units. If SearchInSubDir == true use parameter KLHST_AD_ORGUNIT_GP else use KLHST_AD_ORGUNIT | | +---KLHST_AD_GROUP = (paramInt)17069 - Active Directory group ID. See KLHST_AD_GROUP | | +---Query = (paramString)"(&(KLHST_AD_ORGUNIT_GP=432)(KLHST_AD_GROUP=17069))" | +---AppPageSettings (paramParams) - Application subcontainer | | +---HasAv = (paramInt)1 - Antivirus installed (1 - yes, 0 - no). Placed in query as KLHST_WKS_STATUS & 0x00000010 | | +---Managed = (paramInt)1 - Computer is managed by KSC (1 - yes, 0 - no). Placed in query as KLHST_WKS_STATUS & 0x00000004 ``` -------------------------------- ### Execute klnagchk and retrieve diagnostic logs Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00587_aa322db24d83538a759b6b3ca15a0f0ea.html Initiates the diagnostic utility asynchronously and demonstrates the sequence for checking the action state and obtaining the download URL for the resulting log file. ```cpp strRequestId = RunKlnagchkAsync; pResParams = CheckActionState(strRequestId); strResFilename = pResParams.Get("Products").Get("1103/1.0.0.0").Get("DiagLog"); strResUrl = GetUrlToDownloadFileFromHost(strResFilename); ``` -------------------------------- ### Accessing ServerHierarchy in Python Source: https://support.kaspersky.com/KSC/16.2/KSCAPI/a00610.html Demonstrates how to initialize a connection to the administration server and use the ServerHierarchy object to list child servers and their statuses. ```python server = KlAkOAPI.AdmServer.KlAkAdmServer.Create("https://ksc.example.com:13299", "username", "password", verify = False) oServerHierarchy = KlAkOAPI.ServerHierarchy.KlAkServerHierarchy(server) oChildServers = oServerHierarchy.GetChildServers(-1).RetVal() for oChildServer in oChildServers: print("Server's '" + oChildServer["KLSRVH_SRV_DN"] + "', id=" + str(oChildServer["KLSRVH_SRV_ID"]) \ + " status is " + (lambda: 'Inactive' if oChildServer["KLSRVH_SRV_STATUS"] == 0 else 'Active')()) ```