How to use the shodan.exception.APIError function in shodan

To help you get started, we’ve selected a few shodan examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github achillean / shodan-python / shodan / stream.py View on Github external
# Status code 524 is special to Cloudflare
                # It means that no data was sent from the streaming servers which caused Cloudflare
                # to terminate the connection.
                #
                # We only want to exit if there was a timeout specified or the HTTP status code is
                # not specific to Cloudflare.
                if req.status_code != 524 or timeout >= 0:
                    break
        except Exception:
            raise APIError('Unable to contact the Shodan Streaming API')

        if req.status_code != 200:
            try:
                data = json.loads(req.text)
                raise APIError(data['error'])
            except APIError:
                raise
            except Exception:
                pass
            raise APIError('Invalid API key or you do not have access to the Streaming API')
        if req.encoding is None:
            req.encoding = 'utf-8'
        return req
github achillean / shodan-python / shodan / stream.py View on Github external
try:
            while True:
                req = requests.get(stream_url, params=params, stream=True, timeout=timeout,
                                   proxies=self.proxies)

                # Status code 524 is special to Cloudflare
                # It means that no data was sent from the streaming servers which caused Cloudflare
                # to terminate the connection.
                #
                # We only want to exit if there was a timeout specified or the HTTP status code is
                # not specific to Cloudflare.
                if req.status_code != 524 or timeout >= 0:
                    break
        except Exception:
            raise APIError('Unable to contact the Shodan Streaming API')

        if req.status_code != 200:
            try:
                data = json.loads(req.text)
                raise APIError(data['error'])
            except APIError:
                raise
            except Exception:
                pass
            raise APIError('Invalid API key or you do not have access to the Streaming API')
        if req.encoding is None:
            req.encoding = 'utf-8'
        return req
github achillean / shodan-python / shodan / stream.py View on Github external
def alert(self, aid=None, timeout=None, raw=False):
        if aid:
            stream = self._create_stream('/shodan/alert/%s' % aid, timeout=timeout)
        else:
            stream = self._create_stream('/shodan/alert', timeout=timeout)

        try:
            for line in self._iter_stream(stream, raw):
                yield line
        except requests.exceptions.ConnectionError:
            raise APIError('Stream timed out')
        except ssl.SSLError:
            raise APIError('Stream timed out')
github M0tHs3C / Argo / lib / shodanSearch.py View on Github external
"[3]  has_screenshot:yes product:""Yawcam webcam viewer httpd\n"
                          "[4]  has_screenshot:yes product:D-Link/Airlink IP webcam http config""\n")
                    #query="has_screenshot:yes product:""D-Link/Airlink IP webcam http config"    #UN-COMMENT IF YOU HAVE PREMIUM PLAN1
                    return
                elif selection == 8:
                    query= 'WWW-Authenticate: Basic realm="Embedded-Device"'
                elif selection == 9:
                    query = str(input('[-]Enter your custom query: '))

                try:
                    response = api.search(query)
                    with open(path + '/Host/host.txt', "w") as host:
                        for service in response['matches']:
                            host.write(str(service['ip_str'] + ":" + str(service['port'])))# host.write(service['port']
                            host.write("\n")
                except shodan.exception.APIError:
                    print("[!] Bad API, try deleting the api.txt file under the api folder and then recreate the file without modifing it, then re-run the tool\n[!] be advise, the file must be empty and when you must paste the api key without space")
                    answer = input("[?] would you like to try to reset the api key system?  (y/n)  :")
                    if str(answer.lower()) == "y":
                        import platform
                        system = platform.system()
                        if system.lower() == "windows":
                            os.system("del " + path + "/Api/api.txt")
                            os.system("type nul > "+ path + "/Api/api.txt")
                        elif system.lower() == "linux":
                            os.system("rm " + path + "/Api/api.txt")
                            os.system("touch " + path + "/Api/api.txt")
                    else:
                        pass


            except KeyboardInterrupt:
github Te-k / harpoon / harpoon / commands / shodancmd.py View on Github external
res = api.search(args.QUERY)
                print('%i results' % res['total'])
                for r in res['matches']:
                    print('[+] %s (%s): port %s/%i -> %s\n' % (
                            r['ip_str'],
                            r['org'],
                            r['transport'],
                            r['port'],
                            r['data'][:1000]
                        )
                    )
            elif args.subcommand == 'ssh':
                data = {}
                try:
                    res = api.host(args.IP, history=True)
                except shodan.exception.APIError:
                    print("IP not found in Shodan")
                else:
                    for event in res['data']:
                        if event['_shodan']['module'] == 'ssh':
                            if 'ssh' in event:
                                fingerprint = event['ssh']['fingerprint']
                                date = parse(event['timestamp'])
                                if fingerprint not in data:
                                    data[fingerprint] = {
                                        'first': date,
                                        'last': date,
                                        'fingerprint': fingerprint
                                    }
                                else:
                                    if data[fingerprint]['first'] > date:
                                        data[fingerprint]['first'] = date
github achillean / shodan-python / shodan / stream.py View on Github external
# We only want to exit if there was a timeout specified or the HTTP status code is
                # not specific to Cloudflare.
                if req.status_code != 524 or timeout >= 0:
                    break
        except Exception:
            raise APIError('Unable to contact the Shodan Streaming API')

        if req.status_code != 200:
            try:
                data = json.loads(req.text)
                raise APIError(data['error'])
            except APIError:
                raise
            except Exception:
                pass
            raise APIError('Invalid API key or you do not have access to the Streaming API')
        if req.encoding is None:
            req.encoding = 'utf-8'
        return req
github achillean / shodan-python / shodan / client.py View on Github external
if data.status_code == 401:
            try:
                # Return the actual error message if the API returned valid JSON
                error = data.json()['error']
            except Exception as e:
                # If the response looks like HTML then it's probably the 401 page that nginx returns
                # for 401 responses by default
                if data.text.startswith('<'):
                    error = 'Invalid API key'
                else:
                    # Otherwise lets raise the error message
                    error = u'{}'.format(e)

            raise APIError(error)
        elif data.status_code == 403:
            raise APIError('Access denied (403 Forbidden)')

        # Parse the text into JSON
        try:
            data = data.json()
        except ValueError:
            raise APIError('Unable to parse JSON response')

        # Raise an exception if an error occurred
        if type(data) == dict and 'error' in data:
            raise APIError(data['error'])

        # Return the data
        return data
github saucer-man / saucerframe / thirdlib / shodan / cli / worldmap.py View on Github external
else:
            if self.last_fetch + self.polling_interval <= epoch_now:
                refresh = True
        
        if refresh:
            try:
                # Grab 20 banners from the main stream
                banners = []
                for banner in self.api.stream.banners():
                    if 'location' in banner and banner['location']['latitude']:
                        banners.append(banner)
                    if len(banners) >= 20:
                        break
                self.data = banners
                self.last_fetch = epoch_now
            except APIError:
                raise
        return refresh
github achillean / shodan-python / shodan / helpers.py View on Github external
# Exit out of the loop
            break
        except Exception:
            error = True
            tries += 1

    if error and tries >= retries:
        raise APIError('Unable to connect to Shodan')

    # Check that the API key wasn't rejected
    if data.status_code == 401:
        try:
            raise APIError(data.json()['error'])
        except (ValueError, KeyError):
            pass
        raise APIError('Invalid API key')

    # Parse the text into JSON
    try:
        data = data.json()
    except Exception:
        raise APIError('Unable to parse JSON response')

    # Raise an exception if an error occurred
    if type(data) == dict and data.get('error', None):
        raise APIError(data['error'])

    # Return the data
    return data
github achillean / shodan-python / shodan / helpers.py View on Github external
if data.status_code == 401:
        try:
            raise APIError(data.json()['error'])
        except (ValueError, KeyError):
            pass
        raise APIError('Invalid API key')

    # Parse the text into JSON
    try:
        data = data.json()
    except Exception:
        raise APIError('Unable to parse JSON response')

    # Raise an exception if an error occurred
    if type(data) == dict and data.get('error', None):
        raise APIError(data['error'])

    # Return the data
    return data