def lock(self): validate_creds_exists(self.app) db = DBWrapper(self.app.creds) command_client = APIClient(db.get_configure()).get_command_api_client() enterprise_id = db.get_enterprise_id() device_client = APIClient(db.get_configure()).get_device_api_client() if self.app.pargs.device: device_name = self.app.pargs.device kwargs = {'name': device_name} try: search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[device-command-lock] Device does not exist with name {device_name}' ) self.app.render( f'Device does not exist with name {device_name}') return response = search_response.results[0] device_id = response.id except ApiException as e: self.app.log.error( f"[device-command-lock] Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return else: device = db.get_device() if not device or not device.get('id'): self.app.log.debug( '[device-command-lock] There is no active device.') self.app.render('There is no active device.') return device_id = device.get('id') command_request = CommandRequest(command=DeviceCommandEnum.LOCK.name) try: response = command_client.run_command(enterprise_id, device_id, command_request) except ApiException as e: self.app.log.error( f"[device-command-lock] Failed to fire the lock command: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return if not self.app.pargs.json: renderable = self._command_basic_response(response) self.app.render(renderable, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: renderable = self._command_basic_response(response, OutputFormat.JSON) self.app.render(renderable, format=OutputFormat.JSON.value)
def set_active(self): validate_creds_exists(self.app) db = DBWrapper(self.app.creds) device_client = APIClient(db.get_configure()).get_device_api_client() enterprise_id = db.get_enterprise_id() if self.app.pargs.name: device_name = self.app.pargs.name kwargs = {'name': device_name} try: search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[device-active] Device does not exist with name {device_name}' ) self.app.render( f'Device does not exist with name {device_name}') return response = search_response.results[0] db.set_device({ 'id': response.id, 'name': response.device_name }) except ApiException as e: self.app.log.error( f"[device-active] Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return else: device = db.get_device() if device is None or device.get('name') is None: self.app.log.debug( '[device-active] There is no active device.') self.app.render('There is no active device.') return device_id = device.get('id') try: response = device_client.get_device_by_id( enterprise_id, device_id) except ApiException as e: self.app.log.error( f"[device-active] Failed to show active device: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return if not self.app.pargs.json: renderable = self._device_basic_response(response) self.app.render(renderable, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: renderable = self._device_basic_response(response, OutputFormat.JSON) self.app.render(renderable, format=OutputFormat.JSON.value)
def wipe(self): validate_creds_exists(self.app) db = DBWrapper(self.app.creds) command_client = APIClient(db.get_configure()).get_command_api_client() enterprise_id = db.get_enterprise_id() device_client = APIClient(db.get_configure()).get_device_api_client() if self.app.pargs.device: device_name = self.app.pargs.device kwargs = {'name': device_name} try: search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len(search_response.results) == 0: self.app.log.debug(f'[device-command-wipe] Device does not exist with name {device_name}') self.app.render(f'Device does not exist with name {device_name}\n') return response = search_response.results[0] device_id = response.id except ApiException as e: self.app.log.error(f"[device-command-wipe] Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}\n") return else: device = db.get_device() if not device or not device.get('id'): self.app.log.debug('[device-command-wipe] There is no active device.') self.app.render('There is no active device.\n') return device_id = device.get('id') external_storage = self.app.pargs.external_storage frp = self.app.pargs.frp if external_storage is None: self.app.log.info('[device-command-wipe] External storage value is empty') self.app.render('External storage value is empty\n') if frp is None: self.app.log.info('[device-command-wipe] Factory reset production value is empty') self.app.render('Factory reset production value is empty\n') command_request = CommandRequest(command_args={"wipe_external_storage": external_storage, 'wipe_FRP': frp}, command=DeviceCommandEnum.WIPE.name) try: response = command_client.run_command(enterprise_id, device_id, command_request) except ApiException as e: self.app.log.error(f"[device-command-wipe] Failed to fire the wipe command: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}\n") return if not self.app.pargs.json: renderable = self._command_basic_response(response) self.app.render(renderable, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: renderable = self._command_basic_response(response, OutputFormat.JSON) self.app.render(renderable, format=OutputFormat.JSON.value)
def show(self): validate_creds_exists(self.app) db = DBWrapper(self.app.creds) device_name = self.app.pargs.device_name device_client = APIClient(db.get_configure()).get_device_api_client() enterprise_id = db.get_enterprise_id() kwargs = {'name': device_name} try: search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[device-show] Device does not exist with name {device_name}' ) self.app.render( f'Device does not exist with name {device_name}\n') return response = search_response.results[0] except ApiException as e: self.app.log.error(f"[device-show] Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}\n") return if self.app.pargs.active: name, _ = self.get_name_and_tags_from_device(response) db.set_device({'id': response.id, 'name': name}) if not self.app.pargs.json: renderable = self._device_basic_response(response) self.app.render(renderable, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: renderable = self._device_basic_response(response, OutputFormat.JSON) self.app.render(renderable, format=OutputFormat.JSON.value)
def _fetch_device_by_name(self, name: str) -> str: """ Fetch the device entry by its device-name :param name: Device Name :return: uuid str - Device ID as UUID string """ db = DBWrapper(self.app.creds) device_name = name device_client = APIClient(db.get_configure()).get_device_api_client() enterprise_id = db.get_enterprise_id() kwargs = {'name': device_name} search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len(search_response.results) == 0: raise SecureADBWorkflowError(f'Device does not exist with name {device_name}') return search_response.results[0].id
def latest(self): """Command to list status""" validate_creds_exists(self.app) db = DBWrapper(self.app.creds) device_client = APIClient(db.get_configure()).get_device_api_client() enterprise_id = db.get_enterprise_id() if self.app.pargs.device: device_name = self.app.pargs.device kwargs = {'name': device_name} try: search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[status-latest] Device does not exist with name {device_name}' ) self.app.render( f'Device does not exist with name {device_name}') return response = search_response.results[0] device_id = response.id except ApiException as e: self.app.log.error( f"[status-latest] Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return else: device = db.get_device() if not device or not device.get('id'): self.app.log.debug( '[status-latest] There is no active device.') self.app.render('There is no active device.') return device_id = device.get('id') try: response = device_client.get_device_event(enterprise_id, device_id, latest_event=1) except ApiException as e: self.app.log.error( f"[status-latest] Failed to get latest device status: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return battery_level = None battery_temp = None data_download = None data_upload = None memory_storage = None memory_ram = None link_speed = None signal_strength = None if response.results and len(response.results) > 0: data = literal_eval(response.results[0].data) if data.get("powerManagementEvent") and data.get( "powerManagementEvent").get("batteryStatus"): if data.get("powerManagementEvent").get("batteryStatus").get( "batteryLevel"): battery_level = data.get("powerManagementEvent").get( "batteryStatus").get("batteryLevel") if data.get("powerManagementEvent").get("batteryStatus").get( "batteryTemperature"): battery_temp = data.get("powerManagementEvent").get( "batteryStatus").get("batteryTemperature") if data.get("dataUsageStats"): if data.get("dataUsageStats").get("totalDataDownload"): data_download = data.get("dataUsageStats").get( "totalDataDownload") if data.get("dataUsageStats").get("totalDataUpload"): data_upload = data.get("dataUsageStats").get( "totalDataUpload") if data.get("memoryEvents") and len(data.get("memoryEvents")) > 1 and \ data.get("memoryEvents")[1].get("countInMb"): memory_storage = data.get("memoryEvents")[1].get("countInMb") if data.get("memoryEvents") and len(data.get("memoryEvents")) > 0 and \ data.get("memoryEvents")[0].get("countInMb"): memory_ram = data.get("memoryEvents")[0].get("countInMb") if data.get("networkEvent") and data.get("networkEvent").get( "wifiNetworkInfo"): if data.get("networkEvent").get("wifiNetworkInfo").get( "linkSpeed"): link_speed = data.get("networkEvent").get( "wifiNetworkInfo").get("linkSpeed") if data.get("networkEvent").get("wifiNetworkInfo").get( "signalStrength"): signal_strength = data.get("networkEvent").get( "wifiNetworkInfo").get("signalStrength") if not self.app.pargs.json: title = "TITLE" details = "DETAILS" renderable = [{ title: 'battery_level', details: battery_level }, { title: 'battery_temperature', details: battery_temp }, { title: 'data_download', details: data_download }, { title: 'data_upload', details: data_upload }, { title: 'memory_storage', details: memory_storage }, { title: 'memory_ram', details: memory_ram }, { title: 'link_speed', details: link_speed }, { title: 'signal_strength', details: signal_strength }] self.app.render(renderable, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: renderable = { 'battery_level': battery_level, 'battery_temperature': battery_temp, 'data_download': data_download, 'data_upload': data_upload, 'memory_storage': memory_storage, 'memory_ram': memory_ram, 'link_speed': link_speed, 'signal_strength': signal_strength } self.app.render(renderable, format=OutputFormat.JSON.value)
def list(self): """Command to list devices""" validate_creds_exists(self.app) db = DBWrapper(self.app.creds) device_client = APIClient(db.get_configure()).get_device_api_client() enterprise_id = db.get_enterprise_id() state = self.app.pargs.state name = self.app.pargs.name group_name = self.app.pargs.group imei = self.app.pargs.imei brand = self.app.pargs.brand gms = self.app.pargs.gms limit = self.app.pargs.limit offset = self.app.pargs.offset kwargs = {} if state: kwargs['state'] = DeviceState[state.upper()].value if name: kwargs['name'] = name if group_name: kw = {'name': group_name} group_id = None try: group_client = APIClient( db.get_configure()).get_group_api_client() search_response = group_client.get_all_groups(enterprise_id, limit=1, offset=0, **kw) for group in search_response.results: if group.name == group_name: group_id = group.id break except ApiException as e: self.app.log.error(f"[device-list] Failed to list groups: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return if not group_id: group_id = str(uuid.uuid4()) # random uuid kwargs['group'] = group_id if imei: kwargs['imei'] = imei if brand: kwargs['brand'] = brand if gms: kwargs['is_gms'] = gms try: # Find devices in an enterprise response = device_client.get_all_devices(enterprise_id, limit=limit, offset=offset, **kwargs) except ApiException as e: self.app.log.error(f"[device-list] Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return self.app.render(f"Number of Devices: {response.count}") if not self.app.pargs.json: devices = [] label = { 'id': "ID", 'name': "NAME", 'model': "MODEL", 'state': "CURRENT STATE" } for device in response.results: current_state = DeviceState(device.status).name devices.append({ label['id']: device.id, label['name']: device.device_name, label['model']: device.hardware_info.get("manufacturer"), label['state']: current_state }) self.app.render(devices, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: devices = [] for device in response.results: current_state = DeviceState(device.status).name devices.append({ 'id': device.id, 'device': device.device_name, 'model': device.hardware_info.get("manufacturer"), 'state': current_state }) self.app.render(devices, format=OutputFormat.JSON.value)
def devices(self): validate_creds_exists(self.app) db = DBWrapper(self.app.creds) device_client = APIClient(db.get_configure()).get_device_api_client() group_client = APIClient(db.get_configure()).get_group_api_client() enterprise_id = db.get_enterprise_id() if self.app.pargs.group: group_name = self.app.pargs.group kwargs = {'name': group_name} try: search_response = group_client.get_all_groups(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[group-devices] Group does not exist with name {group_name}' ) self.app.render( f'Group does not exist with name {group_name}') return response = search_response.results[0] group_id = response.id except ApiException as e: self.app.log.error( f"[group-devices] Failed to list groups: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return else: group = db.get_group() if group is None or group.get('name') is None: self.app.log.debug('[group-devices] There is no active group.') self.app.render('There is no active group.') return group_id = group.get('id') limit = self.app.pargs.limit offset = self.app.pargs.offset try: response = device_client.get_all_devices(enterprise_id, group=group_id, limit=limit, offset=offset) except ApiException as e: self.app.log.error( f"[group-devices] Failed to list group devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return self.app.render(f"Number of Devices: {response.count}") if not self.app.pargs.json: devices = [] label = { 'id': "ID", 'name': "NAME", 'model': "MODEL", 'state': "CURRENT STATE" } for device in response.results: devices.append({ label['id']: device.id, label['name']: device.device_name, label['model']: device.hardware_info.get("manufacturer"), label['state']: DeviceState(device.status).name }) self.app.render(devices, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: devices = [] for device in response.results: devices.append({ 'id': device.id, 'device': device.device_name, 'model': device.hardware_info.get("manufacturer"), 'state': DeviceState(device.status).name }) self.app.render(devices, format=OutputFormat.JSON.value)
def remove(self): validate_creds_exists(self.app) db = DBWrapper(self.app.creds) group_client = APIClient(db.get_configure()).get_group_api_client() enterprise_id = db.get_enterprise_id() data = DeviceGroupUpdate() if self.app.pargs.group: group_name = self.app.pargs.group kwargs = {'name': group_name} try: search_response = group_client.get_all_groups(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[group-remove] Group does not exist with name {group_name}' ) self.app.render( f'Group does not exist with name {group_name}') return response = search_response.results[0] group_id = response.id except ApiException as e: self.app.log.error( f"[group-remove] Failed to list groups: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return else: group = db.get_group() if group is None or group.get('name') is None: self.app.log.debug('[group-remove] There is no active group.') self.app.render('There is no active group.') return group_id = group.get('id') devices = self.app.pargs.devices if not devices or len(devices) == 0: self.app.log.debug('[group-remove] devices cannot be empty.') self.app.render('devices cannot be empty.') return device_client = APIClient(db.get_configure()).get_device_api_client() request_device_ids = [] for device_name in devices: kwargs = {'name': device_name} try: search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[group-remove] Device does not exist with name {device_name}' ) self.app.render( f'Device does not exist with name {device_name}') return response = search_response.results[0] request_device_ids.append(response.id) except ApiException as e: self.app.log.error(f"Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return device_client = APIClient(db.get_configure()).get_device_api_client() current_device_ids = self._get_group_device_ids( device_client, enterprise_id, group_id) if current_device_ids is None: return latest_devices = list( set(current_device_ids) - set(request_device_ids)) data.device_ids = latest_devices try: response = group_client.partial_update_group( group_id, enterprise_id, data) except ApiException as e: self.app.log.error( f"[group-remove] Failed to remove device from group: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return if not self.app.pargs.json: renderable = self._group_basic_response(response) self.app.render(renderable, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: renderable = self._group_basic_response(response, OutputFormat.JSON) self.app.render(renderable, format=OutputFormat.JSON.value)
def list(self): """Command to list installs""" validate_creds_exists(self.app) db = DBWrapper(self.app.creds) device_client = APIClient(db.get_configure()).get_device_api_client() enterprise_id = db.get_enterprise_id() if self.app.pargs.device: device_name = self.app.pargs.device kwargs = {'name': device_name} try: search_response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not search_response.results or len( search_response.results) == 0: self.app.log.debug( f'[installs-list] Device does not exist with name {device_name}' ) self.app.render( f'Device does not exist with name {device_name}') return response = search_response.results[0] device_id = response.id except ApiException as e: self.app.log.error( f"[installs-list] Failed to list devices: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return else: device = db.get_device() if not device or not device.get('id'): self.app.log.debug( '[installs-list] There is no active device.') self.app.render('There is no active device.') return device_id = device.get('id') app_name = self.app.pargs.appname package_name = self.app.pargs.package install_state = self.app.pargs.state limit = self.app.pargs.limit offset = self.app.pargs.offset kwargs = {} if app_name: kwargs['application_name'] = app_name if package_name: kwargs['package_name'] = package_name if install_state: kwargs['install_state'] = install_state try: response = device_client.get_app_installs(enterprise_id, device_id, limit=limit, offset=offset, **kwargs) except ApiException as e: self.app.log.error(f"[installs-list] Failed to list installs: {e}") self.app.render(f"ERROR: {parse_error_message(self.app, e)}") return self.app.render(f"Total Number of Installs: {response.count}") if not self.app.pargs.json: installs = [] label = { 'id': "ID", 'application_name': "APPLICATION", 'package_name': "PACKAGE", 'version_code': "VERSION", 'install_state': "STATE" } for install in response.results: installs.append({ label['id']: install.id, label['application_name']: install.application.application_name, label['package_name']: install.application.package_name, label['version_code']: install.application.version.version_code, label['install_state']: install.install_state }) self.app.render(installs, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain") else: installs = [] for install in response.results: installs.append({ 'id': install.id, 'application_name': install.application.application_name, 'package_name': install.application.package_name, 'version_code': install.application.version.version_code, 'install_state': install.install_state }) self.app.render(installs, format=OutputFormat.JSON.value)
def get_data(self): validate_creds_exists(self.app) db = DBWrapper(self.app.creds) environment = db.get_configure().get("environment") enterprise_id = db.get_enterprise_id() device_client = APIClient(db.get_configure()).get_device_api_client() device_name = self.app.pargs.device_name if not device_name: self.app.render( f'No device specified. Use the -d, --device option to specify a device\n' ) return kwargs = {'name': device_name} # Fetch device id from device name supplied as parameter try: response = device_client.get_all_devices(enterprise_id, limit=1, offset=0, **kwargs) if not response.results or len(response.results) == 0: self.app.log.debug( f'[device-show] Device does not exist with name {device_name}' ) self.app.render( f'Device does not exist with name {device_name}\n') return device_id = response.results[0].id except ApiException as e: self.app.log.error( f"[device-show] Failed to fetch telemetry info for device {device_name}: {e}" ) self.app.render(f"ERROR: {parse_error_message(self.app, e)}\n") return last = self.app.pargs.last period = self.app.pargs.period statistic = self.app.pargs.statistic from_time = self.app.pargs.from_time if last: current_date = datetime.now() if period == 'hour': from_time = current_date - timedelta(hours=int(last)) elif period == 'day': from_time = current_date - timedelta(days=int(last)) else: from_time = current_date.replace( month=datetime.now().date().month - int(last)) #- timedelta(days=int(last)) from_time = str(from_time).replace(' ', 'T') if '.' not in from_time: from_time = from_time + '.0000Z' if 'Z' not in from_time: from_time = from_time + 'Z' to_time = self.app.pargs.to_time if last: to_time = datetime.now() to_time = str(to_time).replace(' ', 'T') if '.' not in to_time: to_time = to_time + '.0000Z' if 'Z' not in to_time: to_time = to_time + 'Z' if '-' not in self.app.pargs.metric: self.app.render( "ERROR: Metric must be of format {category}-{metric name}\n") return category, metric = self.app.pargs.metric.split('-') # Calling Telemetry Graphs API url = get_telemetry_url(environment, enterprise_id, device_id, category, metric, from_time, to_time, period, statistic) api_key = db.get_configure().get("api_key") response = requests.get(url, headers={'Authorization': f'Bearer {api_key}'}) response_json = response.json() if response.status_code != 200: if response_json.get('meta', {}).get('non_field_errors'): error_list = response_json.get('meta', {}).get('non_field_errors') self.app.render(f"ERRORS: {error_list}\n") elif response_json.get('errors'): self.app.render(f"ERRORS: {response_json.get('errors')}\n") else: #print(response_json, from_time, to_time) self.app.render(f"ERROR: Unknown error occurred\n") return data = response.json().get('data', {}) # Rendering table with populated values label = {'time': "Time", 'value': "Value"} render_data = [] for d in data: render_data.append({label['time']: d['x'], label['value']: d['y']}) if len(render_data) == 0: self.app.render( f"No telemetry data for device {device_name} found between time range\n" ) return self.app.render(f"Telemetry data for device {device_name}") self.app.render(render_data, format=OutputFormat.TABULATED.value, headers="keys", tablefmt="plain")