Python shodan.APIError() Examples

The following are 21 code examples of shodan.APIError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module shodan , or try the search function .
Example #1
Source File: shodantools.py    From ODIN with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def run_shodan_search(self,target):
        """Collect information Shodan has for target domain name. This uses the Shodan search
        instead of host lookup and returns the target results dictionary from Shodan.

        A Shodan API key is required.

        Parameters:
        target      The domain to search for on Shodan
        """
        if self.shodan_api is None:
            pass
        else:
            try:
                target_results = self.shodan_api.search(target)
                return target_results
            except shodan.APIError as error:
                pass 
Example #2
Source File: mcd.py    From memcachedump with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_servers(api_key, continue_flag, outdir):
    api = shodan.Shodan(api_key)
    memcached_servers = []
    try:
        results = api.search("product:memcached")
        print("Results found: {}".format(results["total"]))
        for result in results.get("matches"):
            elem = {"ip_str": result.get("ip_str"), "port": result.get("port")}
            memcached_servers.append(elem)
            print("[ ] Found memcached server at IP: {}".format(result["ip_str"]))
    except shodan.APIError as e:
        print('[-] Shodan error: %s' % e)
    if continue_flag:
        # Get files currently in output directory and remove .csv or .json extension so we just have the IP address
        currentfiles = [os.path.splitext(f)[0] for f in listdir(outdir) if isfile(join(outdir, f))]
        memcached_servers = [x for x in memcached_servers if x not in currentfiles]     
    return memcached_servers 
Example #3
Source File: testShodan_openssl_python2.py    From Mastering-Python-for-Networking-and-Security with MIT License 6 votes vote down vote up
def obtain_host_info(self,IP):
        try:
                host = self.shodanApi.host(IP)
                if len(host) != 0:
                            # Print host info
                            print 'IP: %s' % host.get('ip_str')
                            print 'Country: %s' % host.get('country_name','Unknown')
                            print 'City: %s' % host.get('city','Unknown')
                            print 'Latitude: %s' % host.get('latitude')
                            print 'Longitude: %s' % host.get('longitude')
                            print 'Hostnames: %s' % host.get('hostnames')

                            for i in host['data']:
                               print 'Port: %s' % i['port']
                               
                            return host
        except shodan.APIError, e:
                print ' Error: %s' % e
                return host 
Example #4
Source File: testShodan_openssl_python3.py    From Mastering-Python-for-Networking-and-Security with MIT License 6 votes vote down vote up
def obtain_host_info(self,IP):
        try:
                host = self.shodanApi.host(IP)
                if len(host) != 0:
                            # Print host info
                            print('IP: %s' % host.get('ip_str'))
                            print('Country: %s' % host.get('country_name','Unknown'))
                            print('City: %s' % host.get('city','Unknown'))
                            print('Latitude: %s' % host.get('latitude'))
                            print('Longitude: %s' % host.get('longitude'))
                            print('Hostnames: %s' % host.get('hostnames'))

                            for i in host['data']:
                               print('Port: %s' % i['port'])
                               
                            return host
        except shodan.APIError as e:
                print(' Error: %s' % e)
                return host 
Example #5
Source File: shodantools.py    From ODIN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_shodan_lookup(self,target):
        """Collect information Shodan has for target IP address. This uses the Shodan host lookup
        instead of search and returns the target results dictionary from Shodan.

        A Shodan API key is required.

        Parameters:
        target      The IP address to use for the Shodan query
        """
        if self.shodan_api is None:
            pass
        else:
            try:
                target_results = self.shodan_api.host(target)
                return target_results
            except shodan.APIError as error:
                if error == "Invalid IP":
                    click.secho("[*] A domain resolved to {}, which Shodan has flagged as an invalid \
IP address. Review it and check the hostname in the final results. If it is a valid address, the \
domain may resolve to an internal asset or have a CNAME for an internal asset.",fg="yellow")
                else:
                    pass 
Example #6
Source File: payloadtools.py    From wfuzz with GNU General Public License v2.0 5 votes vote down vote up
def _do_search(self):
        while 1:
            page = self.page_queue.get()
            if page is None:
                self.page_queue.task_done()
                break

            if self._cancel_job:
                self.page_queue.task_done()
                continue

            if self._page_limit > 0 and page >= self._page_limit:
                self.page_queue.task_done()
                self.results_queue.put(None)
                continue

            try:
                results = self.api.search(self._dork, page=page)
                for item in results['matches']:
                    if not self._cancel_job:
                        self.results_queue.put(item)

                self.page_queue.task_done()
                if not self._cancel_job:
                    self.page_queue.put(self._page.inc())
            except shodan.APIError as e:
                self.page_queue.task_done()
                if "Invalid page size" in str(e):
                    self.results_queue.put(None)
                elif "Insufficient query credits" in str(e):
                    self.results_queue.put(None)
                else:
                    self.results_queue.put(e)
                continue 
Example #7
Source File: pureblood.py    From pureblood with MIT License 5 votes vote down vote up
def shodan_host_lookup(self, shodan_host, shl_SHODAN_API_KEY):
        shodan_api = shodan.Shodan(shl_SHODAN_API_KEY)
        try:
            shodan_host_lookup_results = shodan_api.host(shodan_host)
            self.shodan_host_lookup_result = shodan_host_lookup_results
            return self.shodan_host_lookup_result
        except shodan.APIError as e:
            print ('[!] - Error: {0}'.format(e))
            time.sleep(2)
            web_pentest() 
Example #8
Source File: pureblood.py    From pureblood with MIT License 5 votes vote down vote up
def shodan_search(self, query, ss_SHODAN_API_KEY):
        shodan_api = shodan.Shodan(ss_SHODAN_API_KEY)
        try:
            shodan_search_results = shodan_api.search(query)
            self.shodan_search_result = shodan_search_results
            return self.shodan_search_result
        except shodan.APIError as e:
            print ('[!] - Error: {0}'.format(e))
            time.sleep(2)
            web_pentest() 
Example #9
Source File: testShodan_openssl_python2.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def shodanSimpleSearch(self,query):
        try:
            results = self.shodanApi.search(str(query))
            # Show the results
            print 'Results found: %s' % results['total']
            print '-------------------------------------'
            for result in results['matches']:
                print 'IP: %s' % result['ip_str']
                print result['data']
                self.obtain_host_info(result['ip_str'])
                print '--------------------------------------------'
        except shodan.APIError, e:
                print 'Error in search: %s' % e

    #Obtain info IP 
Example #10
Source File: testShodan_openssl_python3.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def shodanSimpleSearch(self,query):
        try:
            results = self.shodanApi.search(str(query))
            # Show the results
            print('Results found: %s' % results['total'])
            print('-------------------------------------')
            for result in results['matches']:
                print('IP: %s' % result['ip_str'])
                print(result['data'])
                self.obtain_host_info(result['ip_str'])
                print('--------------------------------------------')
        except shodan.APIError as e:
                print('Error in search: %s' % e)

    #Obtain info IP 
Example #11
Source File: pureblood.py    From ITWSV with MIT License 5 votes vote down vote up
def shodan_search(self, query, ss_SHODAN_API_KEY):
        shodan_api = shodan.Shodan(ss_SHODAN_API_KEY)
        try:
            shodan_search_results = shodan_api.search(query)
            self.shodan_search_result = shodan_search_results
            return self.shodan_search_result
        except shodan.APIError as e:
            print ('[!] - Error: {0}'.format(e))
            time.sleep(2)
            web_pentest() 
Example #12
Source File: shodanfunctions.py    From osint-combiner with MIT License 5 votes vote down vote up
def to_file_shodan(queries, path_output_file, should_convert, should_add_institutions):
    """Makes a Shodan API call with each given query and writes results to output file
    :param queries: Collection of strings which present Shodan queries
    :param path_output_file: String which points to existing output file
    :param should_convert: Boolean if results should be converted
    :param should_add_institutions: boolean if an institution field should be added when converting
    """
    api = get_new_shodan_api_object()
    nr_total_results = 0
    failed_queries = set()
    for query in queries:
        print('\"' + query + '\"')
        results = 0
        with open(path_output_file, "a") as output_file:
            try:
                for banner in api.search_cursor(query):
                    banner = dict_clean_empty(banner)
                    output_file.write(json.dumps(banner) + '\n')
                    results += 1
                    print('\r' + str(results) + ' results written...', end='')
                print("")
            except shodan.APIError as e:
                print('Error: ', e)
                failed_queries.add(failed_queries)
        nr_total_results += results
    # Print failed queries if present
    if not failed_queries == set():
        print('Failed queries: ', failed_queries)

    print(str(nr_total_results) + ' total results written in ' + path_output_file)
    if should_convert:
        institutions = None
        if should_add_institutions:
            institutions = get_institutions()
        convert_file(path_output_file, 'shodan', institutions) 
Example #13
Source File: seitan.py    From tactical-exploitation with MIT License 5 votes vote down vote up
def search(api, search_str, limit):
    """
    Search with Shodan API
    """

    try:
        res = api.search(search_str, limit=limit)

        for banner in res["matches"]:

            # header
            print("[", end="")
            if "ip_str" in banner and banner["ip_str"]:
                print(banner["ip_str"], end=", ")
            if "hostnames" in banner and banner["hostnames"]:
                for hostname in banner["hostnames"]:
                    print(hostname, end=", ")
            if "os" in banner and banner["os"]:
                print(banner["os"], end=", ")
            if "port" in banner and banner["port"]:
                print(banner["port"], end=", ")
            if "timestamp" in banner and banner["timestamp"]:
                date = banner["timestamp"][:10]
                print(date, end="")
            print("]\n")

            # service information
            if "ssl" in banner and banner["ssl"]["cert"]["subject"]:
                b = banner["ssl"]["cert"]["subject"]
                for field in b:
                    print("{}: {}".format(field, b[field]))
                print()
            if "data" in banner and banner["data"]:
                print(banner["data"].rstrip(), end="\n\n")
        
    except shodan.APIError as err:
        print("\t// error: {}\n".format(err))
        return 0

    return res["total"] 
Example #14
Source File: shodan-prod.py    From PyCk with GNU General Public License v3.0 5 votes vote down vote up
def main():

    API_KEY = input("Enter your shodan api key: ")
    # If you don't want enter your shodan key every time you can define API_KEY as a string like API_KEY = "YOUR_SHODAN_KEY"
    api = shodan.Shodan(API_KEY)
    try:
        prod = input("Enter product name: ")
        res = api.search(prod)

        print("Results found {}".format(res['total']))
        for r in res['matches']:
            print("IP: {}".format(res['ip_str']))
            print(res['data'])
            print("")

    except shodan.APIError as e:
        print("Error: {}".format(e))

    except KeyboardInterrupt:
        print("Exiting...")
        exit(0) 
Example #15
Source File: shodan_api.py    From yeti with Apache License 2.0 5 votes vote down vote up
def fetch(observable, api_key):
        try:
            return shodan.Shodan(api_key).host(observable.value)
        except shodan.APIError as e:
            logging.error('Error: {}'.format(e)) 
Example #16
Source File: device_search.py    From OSINT-SPY with GNU General Public License v3.0 5 votes vote down vote up
def get_device(device_name, json_output=False):
    try:
        api = shodan.Shodan(shodan_api_key)
        results = api.search(device_name)
        time.sleep(5)
        if json_output:
            print(results)
            return
        print(f"Results Found: {results['total']}")
        for result in results['matches']:
            print(f"Ip:: {result['ip_str']} | Organization:: {result['org']} |"
                  f" Domain:: {result['domains']} | ISP:: {result['isp']}")

    except shodan.APIError as e:
        print(e) 
Example #17
Source File: ip_enum.py    From OSINT-SPY with GNU General Public License v3.0 5 votes vote down vote up
def ip_details(ip, json_output=False):
    try:
        api = shodan.Shodan(shodan_api_key)
        host = api.host(ip)
        if json_output:
            print(host)
            return
        print(f'IP Provided:: {ip}')
        format_dict(host, attribute='data')
    except shodan.APIError as e:
        print(e) 
Example #18
Source File: scanIP.py    From NoSQLAttack with GNU General Public License v3.0 5 votes vote down vote up
def scanMongoDBIP():
    SHODAN_API_KEY = "9kwHl4vdqoXjeKl7iXOHMvXGT3ny85Ig";
    api = shodan.Shodan(SHODAN_API_KEY);
    print 'Start Scanning.....'
    try:
        results = api.search('mongoDB')

#        print 'Results found:%s' % results['total']
        for index in range(1,10):
            print str(index)+'_Attacked IP : %s' % results['matches'][index]['ip_str']
#        select = raw_input("Get more IP (y/n)?")
        select = raw_input("Select IP to attack:")
        GlobalVar.set_victim(results['matches'][int(select)]['ip_str'])
        GlobalVar.set_optionSet(0, True)
        GlobalVar.set_myIP('127.0.0.1')
        GlobalVar.set_optionSet(4, True)
        start = raw_input("Start Default Configuration Attack(y/n)?")
        if start == 'y':
            netAttacks(GlobalVar.get_victim(), GlobalVar.get_dbPort(), GlobalVar.get_myIP(), GlobalVar.get_myPort())

#        for result in results['matches']:
#            print 'Attacked IP: %s' % result['ip_str']
            #print result['data']
            #print 'hostnames:' % result['hostnames'];
            #print ' '
    except shodan.APIError, e:
        print 'Error:%s' % e
#if __name__ == "__main__":
#    scanMongoDBIP()
# (1)255.255.255.255 is a broadcast address , beginning with 255 can not be used
# (2)The last ip in each segment is a broadcast address and can not be used by a particular computer . For example, 192.168.1.255 (255 can not be used )
# (3)127.0.0.1 can not be used for communication between computers , 127 beginning unavailable
# (4)0.0.0.0 indicates an invalid address , it can not be used
# (5)10.0.0.0~10.255.255.255   192.168.0.0~192.168.255.255  172.16.0.0~172.31.255.255  are all private address
# (6)169.254.0.0 ~ 169.254.255.255 is assigned by WINDOWS operating system , the emergence of this IP on behalf of your current network can not access the 
Example #19
Source File: pureblood.py    From ITWSV with MIT License 5 votes vote down vote up
def shodan_host_lookup(self, shodan_host, shl_SHODAN_API_KEY):
        shodan_api = shodan.Shodan(shl_SHODAN_API_KEY)
        try:
            shodan_host_lookup_results = shodan_api.host(shodan_host)
            self.shodan_host_lookup_result = shodan_host_lookup_results
            return self.shodan_host_lookup_result
        except shodan.APIError as e:
            print ('[!] - Error: {0}'.format(e))
            time.sleep(2)
            web_pentest() 
Example #20
Source File: gasmask.py    From gasmask with GNU General Public License v3.0 4 votes vote down vote up
def ShodanSearch(api_key, domain, value, uas, proxies, timeouts, limit=0):

    api = shodan.Shodan(api_key)
    server = "shodan.io"
    counter = 0
    quantity = 10
    step = 10
    vhosts = []
    results = ''

    # Warning: Shodan api needs a payment plan!
    # Wrap the request in a try/ except block to catch errors
    try:
        # Search by hostname
        query = 'hostname:' + domain
        return api.search(query)

    except shodan.APIError as e:
        print('Error: %s' % e)

    while counter <= limit:
        try:
            url = "https://" + server + "/search?q=ip%3A" + value + "&go=&count=" + str(
                quantity) + "&FORM=QBHL&qs=n&first=" + str(counter)
            s = requests.Session()
            r = s.get(url, verify=False, headers={'User-Agent': PickRandomUA(uas)},
                      proxies=proxies)
            if r.status_code != 200:
                print("[-] Something is going wrong (status code: {})".format(r.status_code))
                return [], []
            results += r.text
        except Exception as e:
            print(e)

        time.sleep(PickRandomTimeout(timeouts))
        counter += step

    all_hostnames = GetHostnamesAll(results)

    for x in all_hostnames:
        x = re.sub(r'[[\<\/?]*[\w]*>]*', '', x)
        x = re.sub('<', '', x)
        x = re.sub('>', '', x)
        vhosts.append(x)

    return sorted(set(vhosts))


# ##################  Reports  ######################## # 
Example #21
Source File: shodan.py    From ph0neutria with Apache License 2.0 4 votes vote down vote up
def get_malwareurl_list():
    """Query Shodan for C2 servers hosting malware.

    Returns:
    - url_list: (type: MalwareUrl list) list of malware URLs.
    """
    api = shodan.Shodan(API_KEY)

    try:
        LOGGING.info('Querying Shodan for C2 servers...')

        limit_date = (
            date.today() -
            timedelta(
                days=BASECONFIG.malware_days)).strftime('%d/%m/%Y')
        search_term = 'category:malware after:{0}'.format(limit_date)

        results = api.search(search_term, page=1)

        LOGGING.info('Waiting a second...')
        time.sleep(1)

        results_num = int(results['total'])
        LOGGING.info('Results found: {0}'.format(str(results_num)))

        pages = int(math.ceil(results_num / 100))

        if pages > 0:
            url_list = []

            for n in range(1, pages + 1):
                if n > 1:
                    results = api.search(search_term, page=n)

                LOGGING.info('Fetched page {0} of {1}...'.format(n, pages))

                for result in results['matches']:
                    ip_list = get_urls_for_ip(result['ip_str'], NAME)

                    if len(ip_list) > 0:
                        url_list.extend(ip_list)

            return url_list

        else:
            return []

    except shodan.APIError as e:
        LOGGING.info('Error: {0}'.format(e))

    except Exception as e:
        LOGGING.info('Error: {0}'.format(e))

    return []