Showing results for 
Search instead for 
Did you mean: 

[Python] Add the systems to a system group depends on where they are (geo location)

Rising Star I
Rising Star I

Last time I wrote a pwsh script for grouping the systems based on its geo location, in order to give our Python SDK a go, I ported the whole thing in Python 😃

First thing first

  • Clone the SDK repo (the "latest" branch) to your machine. 
  • Run the cmd to install these packages:
    pip3 install  /Path/to/repo/jcapi-python-latest/jcapiv1                  
    pip3 install /Path/to/repo/jcapi-python-latest/jcapiv2                 


  • Encouraged to run this script on a schedule - ideally at least once a day.
  • This script can be ran on any server / VM / device which tasked to run jobs - with Python installed.
  • Simply change the variable "backTrackDays" to any number of days suitable in your env.
  • Set a large number of "backTrackDays" (like 10000) if you are running this for the first time.
  • Use a staggered approach by setting the "backTrackDays" if you have a large number of flee. - i.e. first do 10 days back, then 20 days back etc.
  • Location info is fetched by "remoteIP" of the system and a query to[IPAddress]

Here is the code


import jcapiv1,jcapiv2,requests,json,datetime,os

from import ApiException
from import ApiException

from datetime import datetime
from datetime import timedelta

apiKey = 'your-jc-api-key'

backTrackDays = 1 # Recommended interval

# Setting V1 api config
config_V1 = jcapiv1.Configuration()
config_V1.api_key['x-api-key'] = apiKey

# Setting V2 api config
config_V2 = jcapiv2.Configuration()
config_V2.api_key['x-api-key'] = apiKey

# Getting the API instances ready
jcSystemApiInstance = jcapiv1.SystemsApi(jcapiv1.ApiClient(config_V1))
jcSysGroupApiInstance = jcapiv2.SystemGroupsApi(jcapiv2.ApiClient(config_V2))

def getGeoFromIP(IP):
    url = "" + IP
    r = requests.get(url)
    return r.json()

def anchorDate (backTrackDays):
    # Using UTC by default
    now = datetime.utcnow()
    backDate = - timedelta(days=backTrackDays))
    return backDate

# Search if any new systems created since the backTrackDays

backDate = anchorDate(backTrackDays)
systemFilter = f"created:$gt:{backDate}"
jcSystems = jcSystemApiInstance.systems_list(filter=systemFilter).to_dict()['results']

# Add the new systems to the geo orientated group according to remote IP
if [] != jcSystems:

    for system in jcSystems:
        geoLocale = getGeoFromIP(system['remote_ip'])
        sysGroupName = geoLocale['country'] + "_" + system['os_family']

        # Check if the sys group exists
        filter = [f"name:eq:{sysGroupName}"]
        jcSysGroup = jcSysGroupApiInstance.groups_system_list(filter=filter)

        addSysGroupMemberBody = {

        # If the sys group is not created:
        # Add the system to the group
        if [] == jcSysGroup:
            ## Create the group
                createSysGroupBody = {'name':sysGroupName}
                newGroup = jcSysGroupApiInstance.groups_system_post(body=createSysGroupBody)
                print(f"Sys Group {} created!")
            except ApiException as error:
                print(f"Error: {error}")

            ## Add the system to the group
                addSysGroupMember = jcSysGroupApiInstance.graph_system_group_members_post(,body=addSysGroupMemberBody)
                print(f"System {system['hostname']} added to group {}!")
            except ApiException as error:
                print(f"Error: {error}")
                jcsysGroupMember = jcSysGroupApiInstance.graph_system_group_members_post(group_id=jcSysGroup[0].id,body=addSysGroupMemberBody)
                print(f"System {system['hostname']} added to group {jcSysGroup[0].name}!")
            except ApiException as error:
                print(f"System {system['hostname']} Already Exists in {jcSysGroup[0].name} group!")            

    print(f"Phew! No systems has been create for the past {backTrackDays} days, take a day off!")



You Might Like

New to the site? Take a look at these additional resources:

Community created scripts:

Our new Radical Admin blog:

Keep up with Product News:

Read our community guidelines

Ready to join us? You can register here.