Package: magnetsdk2
Niddel Magnet v2 API Python SDKA simple client that allows idiomatic access to theNiddel Magnet v2
REST API. Uses the wonderfulrequestspackage to perform the
requests.Release history:https://github.com/Niddel/magnet-api2-sdk-python/releasesConfiguring CredentialsThere are a couple of ways to let theConnectionobject know which
API key to use. The simplest one is to pass one explicitly to its
constructor:frommagnetsdk2importConnectionconn=Connection(api_key="my secret API key")If an explicit API key is not provided, theConnectionconstructor
will look for one first in theMAGNETSDK_API_KEYenvironment
variable and failing that in thedefaultprofile of the
configuration file.You can add different API keys to a configuration file with different
profiles by creating a file called.magnetsdk/configunder the
current user’s home directory. It is a basic Python configuration file
that looks like the following:[default]
api_key=my secret api key

[profile2]
api_key=another secret api keySo in this case you could create a connection to use either API key as
follows:frommagnetsdk2importConnectionconn_default=Connection()# uses default profileconn_profile2=Connection(profile='profile2')# use profile2 explicitlyUsing the SDKIt’s as simple as creating aConnectionobject and using it to
perform queries. This small example shows you how to print out all of
the organizations the configured API key has access to.importjsonfrommagnetsdk2importConnectionconn=Connection()fororginconn.iter_organizations():print(json.dumps(org,indent=4))Downloading Only New AlertsA common scenario for using the SDK is downloading only new alerts over
time, typically to feed an integration with a 3rd party SIEM or
ticketing system. In order to implement this, the concept of a
persistent iterator that saves its state on a JSON file is provided in
the SDK:frommagnetsdk2importConnectionfrommagnetsdk2.iteratorimportFilePersistentAlertIteratorconn=Connection()# replace xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx with a valid organization IDalert_iterator=FilePersistentAlertIterator('persistence.json',conn,'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')foralertinalert_iterator:try:# try to process alert in some wayprint(alert)except:alert_iterator.load()# on failure, reload iterator so last alert doesn't count as processedelse:alert_iterator.save()# on success, save iterator so last alert counts as processedIf you run this same code multiple times, it should ever only output
alerts it hasn’t processed before, provided filepersistence.jsonis
not tampered with and remains available for reading and writing.You save the current state of the iterator with thesavemethod. If
you tried to process an alert and failed, you can simply not save the
iterator and reload the previous consistent state from disk using theloadmethod.Though the provided implementation saves the data to a JSON file, it is
easy to add other means of persistence by creating subclasses ofmagnetsdk2.iterator.AbstractPersistentAlertIteratorthat implement
the abstract_saveand_loadmethods.Command-line UtilityStarting with version 1.2.0, the package installs aniddelcommand-line utility which can be used to perform most of the same
functionalities available on the SDK. First install the package:$pipinstallmagnetsdk2Then, you can see that a--profileoption can be provided to select
an alternative API key from~/.magnetsdk/config, as described
previously:$niddel-husage:niddel[-h][-pPROFILE][-i][-v][-oOUTFILE]{me,organizations,alerts,logs}...Command-lineutilitytointeractwiththeNiddelMagnetv2API(v1.4.1)positionalarguments:{me,organizations,alerts,logs}medisplayAPIkeyownerinformationorganizationslistbasicorganizationinformationalertslistanorganization'salertslogsupload,downloadorlistlogfilesoptionalarguments:-h,--helpshowthishelpmessageandexit-pPROFILE,--profilePROFILEwhichprofile(from~/.magnetsdk/config)toobtainAPIkeyfrom-i,--indentindentJSONoutput-v,--verbosesetverbosemode-oOUTFILE,--outfileOUTFILEdestinationfiletowriteto,ifexistswillbeoverwrittenYou can even use a persistent alert iterator by providing a file name
with--persistwhen listing alerts:$niddelalerts-husage:niddelalerts[-h][--startSTART][-pPERSIST][-f{json,cef}]organizationlistanorganization's alerts

positional arguments:
  organization          ID of the organization

optional arguments:
  -h, --help            show this help message and exit
  --start START         initial batch date to process in YYYY-MM-DD format
  --cursor CURSOR       latest cursor returned setting the initial batch of alerts
  -p PERSIST, --persist PERSIST
                        file to store persistent state data, to ensure only
                        alerts that haven'tbeenseenbeforearepartoftheoutput-f{json,cef},--format{json,cef}formatinwhichtooutputalertsKeep in mind that the persistence state is only saved immediately before
the command exits, after all unprocessed alerts have been printed to
stdout. So if the CLI utility is interrupted or if an exception occurs
mid-processing, no state is saved and any alerts output in this failed
execution are not considered processed.The default output format for alerts is JSON, but if you provide--formatcefthen theArcSight Common Event
Formatwill be used instead.