Python shodan.Shodan() Examples

The following are 30 code examples of shodan.Shodan(). 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: sh4d0m.py    From N4xD0rk with GNU General Public License v3.0 6 votes vote down vote up
def shodan_ip_search(shodan_search_object, shodan_search_ip):
    port_target = []
    result = ""
    try:
        print "\nSearching Shodan for info about " + shodan_search_ip + "...\n"
        # Search Shodan
        result = shodan_search_object.host(shodan_search_ip)
        try:
            for i in result['data']:
               print 'Port: %s' % i['port']
               port_target.append(i['port'])
        except Exception as e:
            print e
    except Exception as e:
        print e
    return port_target 
Example #3
Source File: shodantools.py    From ODIN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_shodan_resolver(self,target):
        """Resolve a hosname to an IP address using the Shodan API's DNS endpoint.
        
        A Shodan API key is required.

        Parameters:
        target      The hostname to resolve to an IP address using Shodan
        """
        if not helpers.is_ip(target):
            try:
                resolved = requests.get(self.shodan_dns_resolve_uri.format(target,self.shodan_api_key),timeout=self.requests_timeout)
                target_ip = resolved.json()[target]
                return target_ip
            except requests.exceptions.Timeout:
                click.secho("\n[!] The connection to Shodan timed out!",fg="red")
            except requests.exceptions.TooManyRedirects:
                click.secho("\n[!] The connection to Shodan encountered too many redirects!",fg="red")
            except requests.exceptions.RequestException as error:
                click.secho("\n[!] The connection to Shodan encountered an error!",fg="red")
                click.secho("L.. Details: {}".format(error),fg="red")
            return None
        else:
            click.secho("[!] Only a hostname can be resolved to an IP address.",fg="red") 
Example #4
Source File: __init__.py    From ESD with GNU General Public License v3.0 6 votes vote down vote up
def initialize(self, base_dir):
        if self.skey:
            logger.info('Initializing the shodan api.')
            result = os.system('shodan init {skey}'.format(skey=self.skey))
            if result:
                logger.warning('Initializ failed, please check your key.')
                return False
            self.conf.set("shodan", "shodan_key", self.skey)
            self.conf.write(open(base_dir + "/key.ini", "w"))
            self.api = Shodan(get_api_key())
        else:
            from click.exceptions import ClickException
            try:
                key = None if get_api_key() == '' else get_api_key()
                if key:
                    self.api = Shodan(key)
                else:
                    return False
            except ClickException as e:
                logger.warning('The shodan api is empty so you can not use shodan api.')
                return False
        return True 
Example #5
Source File: worldmap.py    From EasY_HaCk with Apache License 2.0 6 votes vote down vote up
def run(self, scr):
        """ Initialize and run the application """
        m = AsciiMap()
        curses.halfdelay(self.sleep)
        while True:
            now = int(time.time())
            refresh = self.fetch_data(now)
            m.set_data(self.data)
            m.draw(scr)
            scr.addstr(0, 1, 'Shodan Radar', curses.A_BOLD)
            scr.addstr(0, 40, time.strftime("%c UTC", time.gmtime(now)).rjust(37), curses.A_BOLD)

            # Key Input
            # q     - Quit
            event = scr.getch()
            if event == ord('q'):
                break

            # redraw window (to fix encoding/rendering bugs and to hide other messages to same tty)
            # user pressed 'r' or new data was fetched
            if refresh:
                m.window.redrawwin() 
Example #6
Source File: hikxploit.py    From Hikxploit with GNU General Public License v3.0 6 votes vote down vote up
def gather_host_shodan():
    api_shodan_key = open(path + "/api.txt","r").read()
    if api_shodan_key == "":
        print(t.red('no shodan api found, please insert a valid one'))
        api_shodan_key_to_file = raw_input('\ntype here:')
        with open(path + "/api.txt", "wb") as api:
            api.write(api_shodan_key_to_file)
        api = shodan.Shodan(api_shodan_key)
    else:
        api = shodan.Shodan(api_shodan_key)
        try:
            query = raw_input("["+t.blue("*")+"]"+ " enter a valid shodan query:")
            response = api.search(query)
            with open(path +'/host.txt',"wb") as host:
                for service in response['matches']:
                    host.write(service['ip_str']+ ":" + str(service['port']))#host.write(service['port']
                    host.write("\n")
        except KeyboardInterrupt:
            print t.red("\n[---]exiting now[---]") 
Example #7
Source File: hikxploit_win.py    From Hikxploit with GNU General Public License v3.0 6 votes vote down vote up
def gather_host_shodan():
    api_shodan_key = open(path + "/api.txt","r").read()
    if api_shodan_key == "":
        print('no shodan api found, please insert a valid one')
        api_shodan_key_to_file = raw_input('\ntype here:')
        with open(path + "/api.txt", "wb") as api:
            api.write(api_shodan_key_to_file)
        api = shodan.Shodan(api_shodan_key)
    else:
        api = shodan.Shodan(api_shodan_key)
        try:
            query = raw_input("["+"*"+"]"+ " enter a valid shodan query:")
            response = api.search(query)
            with open(path +'/host.txt',"wb") as host:
                for service in response['matches']:
                    host.write(service['ip_str']+ ":" + str(service['port']))#host.write(service['port']
                    host.write("\n")
        except KeyboardInterrupt:
            print ("\n[---]exiting now[---]") 
Example #8
Source File: bamf.py    From bamf with GNU General Public License v3.0 6 votes vote down vote up
def _init_shodan(self, shodan_api):
        parameters = {"shodan_api": shodan_api}
        n = self._database.execute("SELECT (SELECT count() from tbl_config) as count").fetchall()[0][0] 
        if isinstance(shodan_api, str):
            if n == 0:
                _ = self._database.execute("INSERT INTO tbl_config (shodan_api) VALUES (:shodan_api)", parameters)
            else:
                _ = self._database.execute("UPDATE tbl_config SET shodan_api=:shodan_api", parameters)

            self._database.commit()

            return shodan.Shodan(shodan_api)

        else:
            if n == 0:
                warn("No Shodan API key found (register a free account at https://account.shodan.io/register)")
            else:
                shodan_api = self._database.execute("SELECT shodan_api FROM tbl_config").fetchall()[0][0]
                if shodan_api:
                    return shodan.Shodan(shodan_api) 
Example #9
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 #10
Source File: shodan.py    From mqtt-pwn with GNU General Public License v3.0 6 votes vote down vote up
def _handle_shodan_from_api(self):
        api = shodan.Shodan(SHODAN_API_KEY)
        table = PrettyTable(field_names=[
            'IP', 'Port', 'ASN', 'Version', 'Organization', 'Hostnames'
        ])

        table.align['ASN'] = "l"
        table.align['Organization'] = "l"
        table.align['Hostnames'] = "l"

        self.print_info('Fetching Shodan data...')

        for item in api.search_cursor('MQTT Connection Code: 0'):
            table.add_row([
                item.get('ip_str', '-'),
                item.get('port', 0),
                item.get('asn', '-'),
                item.get('version', '-'),
                item.get('org', '-'),
                ', '.join(item.get('hostnames', [])) or '-',
            ])

        self.ppaged(msg=str(table))
        export_table(table) 
Example #11
Source File: cveparser.py    From PyParser-CVE with GNU General Public License v3.0 6 votes vote down vote up
def shodan_q():
	global logging
	
	print "\n[" + t.green("+") + "]Please provide a search query. I.e 'cisco' will return all known vulns for that item" 
	
	query = raw_input("\n<" + t.cyan("SHODAN") + ">$ " )
	
	try:
		api = shodan.Shodan(SHODAN_API_KEY)
		results = api.exploits.search(query, 5, 'author, platform, port, type')
	except Exception as e:
		print "\n[" + t.red("!") + "]Critical. An error was raised with the following error message"
		print e
	
	format = json.dumps(results, indent = 2)	
	print format
	
	if logging == True:
		with open('shodan_cve.log', 'ab') as outfile:
			outfile.write(format)
			outfile.close()
			
		print "\n[" + t.green("+") + "]Results have been saved to 'shodan_cve.log' in the current directory." 
Example #12
Source File: exp.py    From POC-EXP with GNU General Public License v3.0 6 votes vote down vote up
def main():
    try:
            # Setup the api
            api = shodan.Shodan(API_KEY)
            query = 'you Know, for'
            for i in range(1,100):
                page = i
                try:
                    result = api.search(query,page)
                except Exception, e:
                    print 'Error: %s and sleep 10 s' % e
                    time.sleep(10)
                    pass
                else:
                    for service in result['matches']:
                        ip = service['ip_str']
                        ip=str(ip)
                        check(ip)
                # Loop through the matches and print each IP
                   
                        
    except Exception, e:
            print 'Error: %s and sleep 10 s' % e
            print i
            sys.exit(1) 
Example #13
Source File: shodanSearch.py    From SPSE with MIT License 6 votes vote down vote up
def shodan_string_search(shodan_search_object, shodan_search_string,
                         hostname_only, page_to_return):

    title()

    # Try/catch for searching the shodan api
    print "[*] Searching Shodan...\n"

    try:
        time.sleep(1)
        # Time to search Shodan
        results = shodan_search_object.search(
            shodan_search_string, page=page_to_return)
        print json.dumps(results)

    except Exception, e:
        if str(e).strip() == "API access denied":
            print "You provided an invalid API Key!"
            print "Please provide a valid API Key and re-run!"
            sys.exit() 
Example #14
Source File: bannergrab.py    From Vaile with GNU General Public License v3.0 6 votes vote down vote up
def grab(web):

    api = shodan.Shodan(SHODAN_API_KEY)
    print(GR+' [*] Resolving hostnames...')
    time.sleep(0.7)
    try:
        print(C+' [!] Parsing information...')
        hostIP = socket.gethostbyname(web)

        print(C+' [!] Setting query parameters...')
        host = api.host(hostIP)

        for item in host['data']:
            print(GR+'\n [+] Port : '+C+ str(item['port']))
            print(G+' [+] Banner :'+C+color.TR2+C+' \n')
            for q in str(item['data']).splitlines():
                if ':' in q:
                    print(O+'    '+q.split(':')[0]+' :'+C+color.TR3+C+G+q.split(':')[1].strip()+C+color.TR2+C)
                else:
                    print(C+'    '+q)
                    time.sleep(0.02)

    except KeyboardInterrupt:
        print(R+' [-] An error occured...\n') 
Example #15
Source File: shodan.py    From recon-ng-marketplace with GNU General Public License v3.0 6 votes vote down vote up
def prep_host(host_data, hostname):
    os = host_data['os']
    hostname = hostname
    host_port = f"{host_data['ip_str']}:{host_data['port']}"
    source = 'Shodan'
    screen_name = host_port
    profile_name = host_port
    profile_url = f"http://{host_port}"
    media_url = f"https://www.shodan.io/host/{host_data['ip_str']}"
    thumb_url = 'https://gravatar.com/avatar/ffc4048d63729d4932fd3cc45139174f?s=300'
    message = (
        f"Hostname: {hostname} | City: {host_data['location']['city']} | State: {host_data['location']['region_code']} "
        f"| Country: {host_data['location']['country_name']} | OS: {os}")
    latitude = host_data['location']['latitude']
    longitude = host_data['location']['longitude']
    time = datetime.strptime(host_data['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')
    return source, screen_name, profile_name, profile_url, media_url, thumb_url, message, latitude, longitude, time 
Example #16
Source File: get_shodn.py    From Just-Metadata with GNU General Public License v3.0 6 votes vote down vote up
def gather(self, all_ips):

        for path, incoming_ip_obj in all_ips.iteritems():

            if incoming_ip_obj[0].shodan_info == "" and incoming_ip_obj[0].ip_address != "":

                if self.api_key is "":
                    print helpers.color("[*] Error: You didn't provide a Shodan API Key!", warning=True)
                    print helpers.color("[*] Please edit Shodan module and add in your API Key.", warning=True)
                else:
                    if incoming_ip_obj[0].shodan_info is '':
                        print "Querying Shodan for information about " + incoming_ip_obj[0].ip_address
                        try:
                            json_result = self.api_object.host(incoming_ip_obj[0].ip_address)
                            incoming_ip_obj[0].shodan_info = json_result
                        except shodan.exception.APIError:
                            incoming_ip_obj[0].shodan_info = "No available information within Shodan about " + incoming_ip_obj[0].ip_address
                        except simplejson.decoder.JSONDecodeError:
                            pass
        return 
Example #17
Source File: poc.py    From pub with GNU General Public License v2.0 6 votes vote down vote up
def iter_targets(targets, shodan_apikey):
        shodan_api = None
        if not shodan:
            LOGGER.warning(
                "[i] starting without shodan support. please pip install shodan to use shodan search strings.")
        else:
            if not shodan_apikey:
                LOGGER.warning("shodan apikey missing! shodan support disabled.")
            else:
                shodan_api = shodan.Shodan(shodan_apikey)

        for target in targets:
            if target.startswith("shodan://"):
                target = target.replace("shodan://", "")
                if shodan_api:
                    for t in shodan_api.search(target)['matches']:
                        yield t['ip_str'], t['port']
            else:
                host,port = target.strip().split(":")
                yield host,int(port) 
Example #18
Source File: payloadtools.py    From wfuzz with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, dork, page, limit):
        key = Facade().sett.get('plugins', 'shodan_apikey')
        if not key:
            raise FuzzExceptMissingAPIKey("A Shodan api key is needed. Please check ~/.wfuzz/wfuzz.ini")

        self.api = shodan.Shodan(key)
        self._dork = dork
        self._page = MyCounter(page)
        self._page_limit = self._page() + limit if limit > 0 else -1

        self.results_queue = Queue(self.MAX_ENQUEUED_RES)
        self.page_queue = Queue()

        self._threads = []

        self._started = False
        self._cancel_job = False 
Example #19
Source File: check-host.py    From HomePWN with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        try: 
            shodan_api = shodan.Shodan(self.args["apishodan"])
            # Lookup the host
            host = shodan_api.host(self.args["rhost"])
        except Exception as e:
            print_error(e)
            print_error("Module has not been launched")
            return
        if host:
            # Print general info
            print_info(f"""
IP: {host['ip_str']}
Organization: {host.get('org', 'n/a')}
Operating System: {host.get('os', 'n/a')}
            """)

            # Print all banners
            for item in host['data']:
                    print_info(f"""
Port: {item['port']}
Banner: {item['data']}
                    """)
        else:
            print_info("No data recollected") 
Example #20
Source File: shodanconnector.py    From grinder with GNU General Public License v2.0 6 votes vote down vote up
def search(
        self, query: str, max_records=DefaultValues.SHODAN_DEFAULT_RESULTS_QUANTITY
    ) -> None:
        """
        Search for defined query in Shodan database
        :param query: query to search for
        :param max_records: quantity of max records to search
        :return: None
        """
        try:
            results_generator = self.api.search_cursor(query, minify=True)
            self.results = list(islice(results_generator, max_records))
            self._remove_unused_fields_in_vulns()
            self.shodan_results_count = self.api.count(query).get("total")
        except (APIError, APITimeout) as api_error:
            print(f"Shodan API error: {api_error}")
        self.real_results_count = len(list(self.results)) 
Example #21
Source File: shodan.py    From AttackSurfaceMapper with GNU General Public License v3.0 6 votes vote down vote up
def port_scan(hostx, key, counter):
    api = shodan.Shodan(key)
    numports = 0

    for IP in hostx.resolved_ips:
        try:
            query = api.host(IP.address)
            IP.ports = query['ports']
            IP.vulns = query['vulns']
            IP.server = query['server']
            # print (query['vulnerabilities'])
            counter.ports = counter.ports + len(hostx.ports)
            counter.vulns = counter.vulns + len(hostx.vulns)
        except:
            time.sleep(1)
            continue 
Example #22
Source File: shodancmd.py    From harpoon with GNU General Public License v3.0 6 votes vote down vote up
def add_arguments(self, parser):
        subparsers = parser.add_subparsers(help='Subcommand')
        parser_a = subparsers.add_parser('ip', help='Get information on an IP address')
        parser_a.add_argument('IP', help='IP to be searched')
        parser_a.add_argument('--history', '-H', action='store_true',
                help='Also display historical information')
        parser_a.add_argument('-v', '--verbose', action='store_true',
                help="Verbose mode (display raw json)")
        parser_a.add_argument('-s', '--summary', action='store_true',
                help="Only display information for ports 22, 80 and 443")
        parser_a.set_defaults(subcommand='ip')
        parser_b = subparsers.add_parser('search', help='Search in shodan')
        parser_b.add_argument('QUERY', help='Query')
        parser_b.set_defaults(subcommand='search')
        parser_c = subparsers.add_parser('ssh', help='Write ssh history from Shodan historical data')
        parser_c.add_argument('IP', help='IP address')
        parser_c.set_defaults(subcommand='ssh')
        self.parser = parser 
Example #23
Source File: worldmap.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def main(argv=None):
    """ Main function / entry point """
    from shodan import Shodan
    from shodan.cli.helpers import get_api_key

    api = Shodan(get_api_key())
    return launch_map(api) 
Example #24
Source File: shodanseeker.py    From shodan-seeker with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, api_key=None, proxies=None):
        self.api_key = api_key
        self.proxies = proxies
        self.api = Shodan(self.api_key, self.proxies)
        self.force = False 
Example #25
Source File: shodansearch.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def __init__(self, host):
        self.host = host
        self.key = "oCiMsgM6rQWqiTvPxFHYcExlZgg7wvTt"
        if self.key == "":
            print "You need an API key in order to use SHODAN database. You can get one here: http://www.shodanhq.com/"
            sys.exit()
        self.api = Shodan(self.key) 
Example #26
Source File: shodantools.py    From ODIN with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        """Everything that should be initiated with a new object goes here."""
        try:
            self.shodan_api_key = helpers.config_section_map("Shodan")["api_key"]
            self.shodan_api = shodan.Shodan(self.shodan_api_key)
        except Exception:
            self.shodan_api = None
            click.secho("[!] Did not find a Shodan API key.",fg="yellow") 
Example #27
Source File: get_shodn.py    From Just-Metadata with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.cli_name = "Shodan"
        self.description = "Requests Shodan for information on provided IPs"
        self.api_key = ""
        self.api_object = shodan.Shodan(self.api_key) 
Example #28
Source File: shodan_utility.py    From pentesting-multitool with GNU General Public License v3.0 5 votes vote down vote up
def settingApi(self):
        try:
            print("Please, set your APIKey here:")
            shodanKeyString = getpass('API Key:' )
            self.shodanApi = shodan.Shodan(shodanKeyString)
        except:
            print("The specified APIKey is invalid, please insert another one.")
            exit() 
Example #29
Source File: shodanfunctions.py    From osint-combiner with MIT License 5 votes vote down vote up
def get_new_shodan_api_object():
    """Returns initialised Shodan API object"""
    config = configparser.ConfigParser()
    config.read(os.path.dirname(os.path.realpath(__file__)) + "/config.ini")
    key = (config['osint_sources']['SHODAN_API_KEY'])
    return shodan.Shodan(key) 
Example #30
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"]