achillean / shodan-python

The official Python library for Shodan
https://developer.shodan.io
Other
2.52k stars 569 forks source link

Add / remove ips from existing alert #179

Closed Caleb-Wishart closed 1 year ago

Caleb-Wishart commented 1 year ago

Hi,

I've recently come across the position whereby I have needed to add some IPs to an existing alert and wanted to try and use the CLI so as to avoid the web interface.

I discovered that this was not a direct option and could only be achieved by editing the JSON file of an export and then importing.

Alternatively, I saw the edit_alert function but that only allows for uploading a set of ips which ignores existing values.

As such I have created 2 short functions which will facilitate the addition or removal of a set of ips from an existing alerts filters.

    def alert_add_ip(self, aid, ip):
        """Adds any listed IPs that should be monitored by the specified alert.
        :param aid: Alert ID
        :type name: str
        :param ip: Network range(s) to monitor
        :type ip: str OR list of str
        :returns: A dict describing the alert
        """
        if isinstance(ip, str):
            ip = [ip]

        alert = self.alerts(aid=aid)
        existing_ip = alert["filters"]["ip"]

        existing_ip.extend(ip)

        return self.edit_alert(aid, existing_ip)

    def alert_remove_ip(self, aid, ip):
        """Removes any listed IPs from the specified alert.
        :param aid: Alert ID
        :type name: str
        :param ip: Network range(s) to stop monitoring
        :type ip: str OR list of str
        :returns: A dict describing the alert
        """
        if isinstance(ip, str):
            ip = [ip]

        alert = self.alerts(aid=aid)
        existing_ip = alert["filters"]["ip"]

        for iprange in ip:
            try:
                existing_ip.remove(iprange)
            except ValueError:
                pass

        return self.edit_alert(aid, existing_ip)

If the alert does not exist then the APIError would be raised to maintain consistency with other functions. These functions can take a single or list of ips in the style of edit_alert.

I would raise a pull request but since these functions are adding additional functionality around the API implementation and not representing a direct API feature I figured I would raise an issue to first see if this would be a valid pull request.

Thanks.

Caleb-Wishart commented 1 year ago

Withdrawing due to lack of interest.