def _shodan_report_(self, evidence): """ Return True if the call to the shodan API has worked properly """ try: api = Shodan(API_KEY_SHODAN) ips = [] for key, val in tqdm(evidence.items(), desc="Hostname resolution"): if "ip" not in key: ips.append(self.hostname_resolver(val)) else: ips.append(val) ip_info = {} for key, val in tqdm(enumerate(ips), desc="Wait for Shodan report", total=len(ips)): try: ip_info['ip' + str(key)] = api.host(val) json_writer("./shodan_report/ip" + str(key), ip_info['ip' + str(key)]) except Exception as e: print('Error: {}: {}'.format(val, e), end="\r") pass time.sleep(2) except Exception as e: print('Error: {}'.format(e)) sys.exit(1) return True
class ShodanIO(Module): def __init__(self, b): super().__init__(b) self.key = self.bot.config.get('apikeys', 'shodan') if not self.key: raise SakariException('Couln\'t find api key for Shodan.') self.shodan = Shodan(self.key) @Command('shodan') def query(self, c, e, args): try: result = self.shodan.count(' '.join(args)) c.privmsg(get_target(c, e), 'Found {} results.'.format(result)) except APIError as er: c.privmsg(get_target(c, e), '\x02Error:\x0f {}'.format(er.value)) @Command('shost', 'shodanhost') def host(self, c, e, args): try: result = self.shodan.host(args[0]) if result: c.privmsg(get_target(c, e), 'Available ports: {' + ', '.join([str(n['port']) for n in result['data']]) + '}.') except APIError as er: c.privmsg(get_target(c, e), '\x02Error:\x0f {}'.format(er.value))
def shodan_scan_task(id): SHODAN_API_KEY = keys['keys']['shodan'] device = Device.objects.get(id=id) api = Shodan(SHODAN_API_KEY) try: # Search Shodan results = api.host(device.ip) # Show the results total = len(results['ports']) for counter, i in enumerate(results['data']): product = '' tags = "" if 'product' in i: product = i['product'] if 'tags' in i: tags = i['tags'] print(counter) device1 = ShodanScan(device=device, products=product, ports=str(i['port']), module=i['_shodan']['module'], tags=tags) device1.save() current_task.update_state(state='PROGRESS', meta={'current': counter, 'total': total, 'percent': int((float(counter) / total) * 100)}) return {'current': total, 'total': total, 'percent': 100} except Exception as e: print(e.args)
def get_shodan_data(indicator, shodan_api_key): data = {} if shodan_api_key: try: shodan_api = Shodan(shodan_api_key) shodan_query = shodan_api.host(indicator) shodan_ports = [] shodan_tags = shodan_query.get('tags') shodan_list_tags = [] if shodan_tags: for tag in shodan_tags: shodan_list_tags.append(tag) else: shodan_tags = 'None' data['shodan_tags'] = ", ".join(shodan_list_tags) data['shodan_region'] = shodan_query.get('region_code', 'None') data['shodan_postal'] = shodan_query.get('postal_code', 'None') data['shodan_country'] = shodan_query.get('country_code', 'None') data['shodan_city'] = shodan_query.get('city', 'None') for item in shodan_query.get('data', []): shodan_ports.append(str(item['port'])) data['shodan_ports'] = ", ".join(shodan_ports) data['shodan_hostnames'] = str( shodan_query.get('hostnames', 'None')) data['shodan_org'] = shodan_query.get('org', 'None') except Exception as err: print('Shodan error for indicator{}: {}'.format( indicator, traceback.format_exception(type(err), err, err.__traceback__))) return data
def shodansearch(self): # shodan script by Sir809 ask = input("Do you have a Shodan API key?: ").lower() if ask == "yes": pass else: self.start() apikey = input("Enter API key: ") try: api = Shodan(apikey) url = input("Ip:> ") print("\n") h = api.host(url) except shodan.exception.APIError: print(Fore.RED + "Invalid API key!") self.start() print(Fore.GREEN + ''' IP: {} Country: {} City: {} ISP: {} Org: {} Ports: {} OS: {} '''.format(h['ip_str'], h['country_name'], h['city'], h['isp'], h['org'], h['ports'], h['os']))
def ShodanMethod(ip): currentPorts = "" api = Shodan('hYOKzljNkOxZI8C2aoJDQX2LdDjhAKEz') try: ipinfo = api.host(ip) except: return "None" for key in ipinfo.keys(): if key == "ports": currentPorts = ipinfo[key] return currentPorts
def main(): api = Shodan('T3YseGLAzQ6pmPAW4qfVyHKAi20gHfX6') h = api.host('84.199.0.254') print(h) print(''' Direccion: {} Ciudad: {} ISP: {} Organizacion: {} Puertos: {} '''.format(h['ip_str'], h['city'], h['isp'], h['org'], h['ports']))
def fetch_from_shodan(): try: api = Shodan(SHODAN_API_KEY) results = api.host(TARGET) services = [] vulns = [] for port in results["ports"]: services.append({ "name": "unknown", "port": port, "protocol": "unknown" }) for cve in results.get("vulns", []): cve_data_url = f"https://cve.circl.lu/api/cve/{cve}" cve_data = requests.get(cve_data_url).json() if "cvss" not in cve_data or "ip" not in cve_data: continue name = cve severity = "med" # exampel severity mapping if cve_data["cvss"] > 6.5: severity = "high" if cve_data["cvss"] > 8: severity = "critical" if cve_data["capec"]: name = cve_data["capec"][0]["name"] desc = cve_data["capec"][0]["summary"] vulns.append({ "name": name, "desc": desc, "severity": severity, "refs": cve_data["references"], "type": "Vulnerability", }) faraday_info = { "hosts": [{ "ip": int2ip(results["ip"]), "description": "hsot found using shodan api", "hostnames": results.get("hostnames", []), "os": results.get("os") or "", "services": services, "vulnerabilities": vulns, }] } print(json.dumps(faraday_info)) except APIError as exception: print("Error: {}".format(exception))
def fetch_from_shodan(): try: api = Shodan(SHODAN_API_KEY) results = api.host(TARGET) services = [] vulns = [] for port in results["ports"]: services.append({ "name": "unknown", "port": port, "protocol": "unknown" }) for cve in results.get("vulns", []): cve_data_url = f'https://cve.circl.lu/api/cve/{cve}' cve_data = requests.get(cve_data_url).json() if 'cvss' not in cve_data or 'ip' not in cve_data: continue name = cve severity = 'med' # exampel severity mapping if cve_data['cvss'] > 6.5: severity = 'high' if cve_data['cvss'] > 8: severity = 'critical' if cve_data['capec']: name = cve_data['capec'][0]['name'] desc = cve_data['capec'][0]['summary'] vulns.append({ "name": name, "desc": desc, "severity": severity, "refs": cve_data['references'], "type": "Vulnerability", }) faraday_info = { "hosts": [{ "ip": int2ip(results['ip']), "description": "hsot found using shodan api", "hostnames": results.get('hostnames', []), "os": results.get('os') or '', "services": services, "vulnerabilities": vulns }] } print(json.dumps(faraday_info)) except APIError as exception: print('Error: {}'.format(exception))
def main(scope_file, tcp_services_file, api_file, outfile): missing = [] f = open(api_file, "r") apikey = (f.read()) f.close() api = Shodan(str(apikey.strip())) scope = open(scope_file, "r") for scope_line in scope: try: IPNetwork(str(scope_line)) except: error = (str(scope_line) + ": ", sys.exc_info()[1]) debug_print(error) continue for ip in IPNetwork(str(scope_line)): try: ipinfo = api.host(str(ip)) except: error = (str(ip) + ": ", sys.exc_info()[1]) debug_print(error) continue host_print(ipinfo) for port in ipinfo['ports']: full_string = (str(ip) + ",TCP," + str(port)) debug_print(full_string) with open(tcp_services_file, "r+") as file: for line in file: if full_string in line: debug_print("match") break else: if arguments["scan"] is True: if (nmap_scan(str(ip), str(port))) is True: missing.append(str(ip) + "," + str(port)) else: missing.append(str(ip) + "," + str(port)) print("Your matrix file is missing: ") print("=============================") print("IP, Port") for ip_port in missing: print(ip_port) if outfile is not None: f = open(outfile, "w") f.write("IP Address, Port\n") for ip_port in missing: f.write(ip_port + "\n") f.close()
class ShodanRepository: def __init__(self): env_file: Dict[str, Optional[str]] = dotenv_values( dotenv_path=f'{abspath(getcwd())}/.env') self.__shodan = Shodan(env_file["SHODAN"]) def search(self, ip_address: str): res = dict(self.__shodan.host(ip_address, minify=True)) return ShodanResponse( domains=res['domains'], hostnames=res['hostnames'], org=res['org'], location= f'{res["country_code"]}, {res["city"]} ({res["latitude"]}, {res["longitude"]})', vulnerabilities=res['vulns'], ports=res["ports"])
def get_service_info(ip): try: api = Shodan('KEY') ipinfo = api.host(ip) except: sys.exit(0) services = {} for service in ipinfo['data']: protocol = service['_shodan']['module'] port = service['port'] services.update({port: protocol}) result = services return result
def green_shodansearch(name_host,shodan_key): # ADD Key config api = Shodan(shodan_key) host = api.host(name_host) # print(ipinfo) # Print general info print(""" IP: {} Organization: {} Operating System: {} """.format(host['ip_str'], host.get('org', 'n/a'), host.get('os', 'n/a'))) # Print all banners for item in host['data']: print(""" Port: {} """.format(item['port']))
class shodan_plug(PluginBase): """This plugin returns any information from Shodan""" name = 'shodan' title = 'Shodan' description = 'Computer Search Engine' cache_timeout = 60 * 60 * 2 types = ['ip'] remote = False def setup(self): from shodan import Shodan self.api = Shodan(self.plugin_config["api_key"]) def get_info(self, arg): info = self.api.host(arg) return info
def shodan_scan_task(id): SHODAN_API_KEY = keys['keys']['shodan'] device = Device.objects.get(id=id) api = Shodan(SHODAN_API_KEY) product = [] tags = [] vulns = [] try: # Search Shodan results = api.host(device.ip) # Show the results total = len(results['ports']) print(total) for counter, i in enumerate(results['data']): if 'product' in i: product.append(i['product']) if 'tags' in i: for j in i['tags']: tags.append(j) current_task.update_state(state='PROGRESS', meta={ 'current': counter, 'total': total, 'percent': int((float(counter) / total) * 100) }) if 'vulns' in results: vulns = results['vulns'] ports = results['ports'] device1 = ShodanScan(device=device, products=product, ports=ports, tags=tags, vulns=vulns) device1.save() print(results['ports']) return {'current': total, 'total': total, 'percent': 100} except Exception as e: print(e.args)
class search_shodan(): def __init__(self, host): self.host = host self.key = "" 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) def run(self): try: host = self.api.host(self.host) return host['data'] except Exception, e: print str(e) print "SHODAN empty reply or error in the call" return "error"
def main(): api = Shodan('zGToTmCJQ8QICf7NYkDEcoFkKI3t0QEi') h = api.host('72.167.226.7') print(''' Direccion: {} Ciudad: {} Isp: {} Org: {} Ports: {} '''.format(h['ip_str'], h['city'], h['isp'], h['org'], h['ports'])) file = open('escaneo.txt', 'a+') for elemento in h['data']: lista = elemento.keys() for l in lista: file.write(str(elemento[l])) file.close()
def main(): ip = '190.210.176.21' api = Shodan('yourshodanapikey') h = api.host(ip) print(''' Direction: {} City: {} ISP: {} Org: {} Ports: {}'''.format(h['ip_str'], h['city'], h['isp'], h['org'], h['ports'])) file = open('scan-{}.txt'.format(ip), 'a+') for elem in h['data']: lst = elem.keys() for l in lst: file.write(str(elem[l])) file.close()
class search_shodan: def __init__(self): self.key = shodanAPI_key if self.key == '': raise MissingKey(True) self.api = Shodan(self.key) self.hostdatarow = [] def search_ip(self, ip): try: ipaddress = ip results = self.api.host(ipaddress) technologies = [] servicesports = [] for result in results['data']: try: for key in result['http']['components'].keys(): technologies.append(key) except KeyError: pass port = str(result.get('port')) product = str(result.get('product')) servicesports.append(str(product) + ':' + str(port)) technologies = list(set(technologies)) self.hostdatarow = [ str(results.get('ip_str')), str(results.get('hostnames')).strip('[]\''), str(results.get('org')), str(servicesports).replace('\'', '').strip('[]'), str(technologies).replace('\'', '').strip('[]') ] except exception.APIError: print(f'{ipaddress}: Not in Shodan') self.hostdatarow = [ ipaddress, "Not in Shodan", "Not in Shodan", "Not in Shodan", "Not in Shodan" ] except Exception as e: print(f'Error occurred in the Shodan IP search module: {e}') finally: return self.hostdatarow
def main(): key = '' api = Shodan(key) data = api.host('123.57.0.34') print(f''' Host: {data["ip_str"]} City: {data["city"]} ISP: {data["isp"]} Org: {data["org"]} Ports: {data["ports"]} ''') f = open('scan.txt', 'a+') for host_data in data['data']: for key in host_data.keys(): f.write(str(host_data[key])) f.close()
def shodan_run(self, ip): if self.api_key is None: sys.exit( f"{Tc.yellow}* Verify that you have provided your API key{Tc.rst}" ) try: api = Shodan(self.api_key) host = api.host(ip) print( f"Org: {host.get('org', 'n/a')}\nOS: {host.get('os', 'n/a')}\n{host.get('isp', 'n/a')}" ) # Print all banners for item in host["data"]: print( f"Port: {item['port']}\nBanner: {item['data']}\nHostnames: {item['hostnames']}" ) except APIError as err: print(err)
def my_shodan(ip): from shodan import Shodan SHODAN_API_KEY = "sphexJZnbzincTbmgrmofXwGNjusg4Wr" api = Shodan(SHODAN_API_KEY) try: host = api.host(ip) except: sys.exit("\n[-] Shodan err,please check your domain or network!!!") print("[+] Shodan search:" + '\n' + '-' * 40) print(""" IP:%s Organization:%s OS:%s """ % (host['ip_str'], host.get('org', 'n/a'), host.get('os', 'n/a'))) for item in host['data']: print "Port:%s\nBanner:%s" % (item['port'], item['data'])
def main(): api = Shodan('shXLINeBiCP4FLh4IhvFiT2Ypbnh5PjK') h = api.host('123.57.0.34') print(''' Direccion: {} Ciudad: {} ISP: {} Org: {} Puertos: {} '''.format(h['ip_str'],h['city'],h['isp'],h['org'],h['ports'])) file = open('escaneo.txt','a+') for elemento in h['data']: lista = elemento.keys() for l in lista: file.write(str(elemento[l])) file.close()
def my_shodan(ip): from shodan import Shodan SHODAN_API_KEY = "sphexJZnbzincTbmgrmofXwGNjusg4Wr" api = Shodan(SHODAN_API_KEY) try: host = api.host(ip) except: sys.exit("\n[-] Shodan err,please check your domain or network!!!") print("[+] Shodan search:" + '\n' + '-' * 40) print(""" IP:%s Organization:%s OS:%s """ % (host['ip_str'], host.get('org','n/a'), host.get('os','n/a'))) for item in host['data']: print "Port:%s\nBanner:%s" % (item['port'], item['data'])
class SearchShodan: def __init__(self): self.key = Core.shodan_key() if self.key is None: raise MissingKey(True) self.api = Shodan(self.key) self.hostdatarow = [] def search_ip(self, ip): try: ipaddress = ip results = self.api.host(ipaddress) technologies = [] servicesports = [] for result in results['data']: try: for key in result['http']['components'].keys(): technologies.append(key) except KeyError: pass port = str(result.get('port')) product = str(result.get('product')) servicesports.append(str(product)+':'+str(port)) technologies = list(set(technologies)) self.hostdatarow = [ str(results.get('ip_str')), str(results.get('hostnames')).strip('[]\''), str(results.get('org')), str(servicesports).replace('\'', '').strip('[]'), str(technologies).replace('\'', '').strip('[]')] except exception.APIError: print(f'{ipaddress}: Not in Shodan') self.hostdatarow = [ipaddress, "Not in Shodan", "Not in Shodan", "Not in Shodan", "Not in Shodan"] except Exception as e: print(f'Error occurred in the Shodan IP search module: {e}') finally: return self.hostdatarow
def shodanSearch(host, key, location): ip = ipaddress.ip_address(host) if ip.is_global is True: appendlog( location, colored( "[*] {0} IP A GLOBAL IP, ATTEMPTING TO PERFORM SHODAN LOOKUP". format(host), 'yellow')) try: api = Shodan(key) lookup = api.host(host) f = open(location + host + "/SHO-" + host + ".txt", "w") # Print general info f.write(""" IP: {0} Organization: {1} Operating System: {2} """.format(lookup['ip_str'], lookup.get('org', 'n/a'), lookup.get('os', 'n/a'))) # Print all banners for item in lookup['data']: f.write(""" Port: {0} Banner: {1} """.format(item['port'], item['data'])) appendlog(location, colored("[+] {0} LOOKUP COMPLETE".format(host), 'green')) except: appendlog( location, colored( "[!] CAN'T GET TO SHODAN RIGHT NOW, YOU'LL HAVE TO DO THIS ANOTHER TIME", 'red')) print("[-] Error: {0}".format(APIError))
class ShodanIntel(AbstractIntelPlugin): LEVEL_MAPPINGS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warn': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } def __init__(self, config): self.api = Shodan('') levelname = config.get('level', 'debug') self.level = self.LEVEL_MAPPINGS.get(levelname, logging.DEBUG) def analyse_hash(self, value, type, node): # TODO(andrew-d): better message? current_app.logger.log(self.level, 'Triggered alert: ') def analyse_domain(self, value, type, node): ipinfo = self.api.host('8.8.8.8') # TODO(andrew-d): better message? current_app.logger.log(self.level, 'Triggered alert: ')
class SearchShodan: def __init__(self): self.key = Core.shodan_key() if self.key is None: raise MissingKey('Shodan') self.api = Shodan(self.key) self.hostdatarow = [] self.tracker: OrderedDict = OrderedDict() async def search_ip(self, ip): try: ipaddress = ip results = self.api.host(ipaddress) asn = '' domains = list() hostnames = list() ip_str = '' isp = '' org = '' ports = list() title = '' server = '' product = '' technologies = list() data_first_dict = dict(results['data'][0]) if 'ip_str' in data_first_dict.keys(): ip_str += data_first_dict['ip_str'] if 'http' in data_first_dict.keys(): http_results_dict = dict(data_first_dict['http']) if 'title' in http_results_dict.keys(): title_val = str(http_results_dict['title']).strip() if title_val != 'None': title += title_val if 'components' in http_results_dict.keys(): for key in http_results_dict['components'].keys(): technologies.append(key) if 'server' in http_results_dict.keys(): server_val = str(http_results_dict['server']).strip() if server_val != 'None': server += server_val for key, value in results.items(): if key == 'asn': asn += value if key == 'domains': value = list(value) value.sort() domains.extend(value) if key == 'hostnames': value = [host.strip() for host in list(value)] value.sort() hostnames.extend(value) if key == 'isp': isp += value if key == 'org': org += str(value) if key == 'ports': value = list(value) value.sort() ports.extend(value) if key == 'product': product += value technologies = list(set(technologies)) self.tracker[ip] = {'asn': asn.strip(), 'domains': domains, 'hostnames': hostnames, 'ip_str': ip_str.strip(), 'isp': isp.strip(), 'org': org.strip(), 'ports': ports, 'product': product.strip(), 'server': server.strip(), 'technologies': technologies, 'title': title.strip()} return self.tracker except exception.APIError: print(f'{ip}: Not in Shodan') self.tracker[ip] = 'Not in Shodan' except Exception as e: # print(f'Error occurred in the Shodan IP search module: {e}') self.tracker[ip] = f'Error occurred in the Shodan IP search module: {e}' finally: return self.tracker
class FindIP(Plugin): def __init__(self, bot): self.bot = bot if not Shodan: print("Shodan not installed.") return self.api = Shodan("KpYC07EoGBtGarTFXCpjsspMVQ0a5Aus") # don look self.interface = bot.util.Interface( "findip", # command name # plugin description "Looks up an IP address with shodan. Args: <IP>", [ # Flags: "<short form> <long form> <description> <1=string or 0=bool>" # "o output Specifies the location of the output file 1", ], self.main, # root function subcommands=[], ).listen() # sets the on message callbacks and parses messages def main(self, message, *args): # include your root flags here query = args[0] # socket.inet_aton(query) try: results = self.api.host(query) except shodan.exception.APIError as e: self.bot.msg(message.target, str(e)) return False output = [] output.append( "OS: " + str(results["os"]) + "\tISP: " + str(results["data"][0]["isp"]) + ( "\tProduct: " + str(results["data"][0]["product"]) if "product" in results["data"][0] else "" ) ) output.append( "City: " + str(results["city"]) + "\tPostal code: " + str(results["postal_code"]) ) output.append( "Area code: " + str(results["area_code"]) + "\t\tCountry code: " + str(results["country_code"]) ) output.append( "Region name: " + str(results["region_code"]) + "\tCountry name: " + str(results["country_name"]) ) output.append( "Latitude: " + str(results["latitude"]) + "\tLongitude: " + str(results["longitude"]) ) ports = [] for data in results["data"]: port = data["port"] if not str(port) in ports: ports.append(str(port)) output.append("Open ports: " + ", ".join(ports)) self.bot.msg(message.target, self.bot.server.code_block("\n".join(output)), follows=message)
''' API_KEY = 'KEY' api = Shodan(API_KEY) netblock = 'NETBLOCK' net = netaddr.IPNetwork(netblock) for IP in net: try: time.sleep(1) fileout = open('shodan_result.stxt', 'a') res = api.host(str(IP), history=True) host_json = {} port_list = [] for banner in sorted(res["data"], key=lambda k: (k["port"], k["timestamp"])): if "timestamp" in banner and banner["timestamp"]: date = banner["timestamp"][:10] else: date = "" port_list.append(str(banner["port"]) + ":" + str(date)) host_json = {'ipaddr': str(IP), 'ports': port_list} fileout.write(str(host_json) + "\n") fileout.close() except Exception as e:
else: todo.append(args.target) except: print("[!] Invalid Target") sys.exit() if args.out: sout = {} for target in todo: # Lookup an IP try: ipinfo = api.host(target) print('[+] target ip \t\t %s' % target) print(' ') #[-] ') print('[-] os \t\t\t %s' % ipinfo['os']) print('[-] org \t\t %s' % ipinfo['org']) print('[-] city \t\t %s' % ipinfo['city']) print('[-] region code \t %s' % ipinfo['region_code']) print('[-] ISP \t\t %s' % ipinfo["isp"]) print('[-] country code \t %s' % ipinfo['country_code']) print('[-] latitude \t\t %s' % ipinfo['latitude']) print('[-] longitude \t\t %s' % ipinfo['longitude']) print(' ') print('[*] hostnames :')
def Search(self): try: Data_to_Cache = [] Directory = General.Make_Directory(self.Plugin_Name.lower()) logger = logging.getLogger() logger.setLevel(logging.INFO) Log_File = General.Logging(Directory, self.Plugin_Name.lower()) handler = logging.FileHandler(os.path.join(Directory, Log_File), "w") handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) Shodan_API_Key = self.Load_Configuration() API_Session = Shodan(Shodan_API_Key) Cached_Data_Object = General.Cache(Directory, self.Plugin_Name) Cached_Data = Cached_Data_Object.Get_Cache() for Query in self.Query_List: try: if self.Type == "Search": Local_Plugin_Name = self.Plugin_Name + "-Search" try: API_Response = API_Session.search(Query) except Exception as e: logging.error( f"{Common.Date()} - {self.Logging_Plugin_Name} - {str(e)}." ) break JSON_Output_Response = Common.JSON_Handler( API_Response).Dump_JSON() Main_File = General.Main_File_Create( Directory, Local_Plugin_Name, JSON_Output_Response, Query, self.The_File_Extensions["Main"]) Output_Connections = General.Connections( Query, Local_Plugin_Name, self.Domain, self.Result_Type, self.Task_ID, self.Plugin_Name.lower()) Current_Step = 0 for Shodan_Item in API_Response["matches"]: Shodan_Item_Module = Shodan_Item['_shodan'][ 'module'] Shodan_Item_Module = Shodan_Item_Module.replace( '-simple-new', '') if Shodan_Item_Module.startswith("http"): Shodan_Item_Host = "" Shodan_Item_Port = 0 if 'http' in Shodan_Item: Shodan_Item_Host = Shodan_Item['http'][ 'host'] Shodan_Item_Response = Shodan_Item['http'][ 'html'] elif 'ip_str' in Shodan_Item and 'domains' in Shodan_Item and len( Shodan_Item['domains']) > 0: Shodan_Item_Host = Shodan_Item['domains'][ 0] Shodan_Item_Response = Shodan_Item['data'] elif 'ip_str' in Shodan_Item and 'domains' not in Shodan_Item: Shodan_Item_Host = Shodan_Item['ip_str'] Shodan_Item_Response = Shodan_Item['data'] if Shodan_Item_Host: if 'port' in Shodan_Item_Host: if int(Shodan_Item['port']) not in [ 80, 443 ]: Shodan_Item_Port = Shodan_Item[ 'port'] if Shodan_Item_Port != 0: Shodan_Item_URL = f"{Shodan_Item_Module}://{Shodan_Item_Host}:{str(Shodan_Item_Port)}" else: Shodan_Item_URL = f"{Shodan_Item_Module}://{Shodan_Item_Host}" Title = f"Shodan | {str(Shodan_Item_Host)}" if Shodan_Item_URL not in Cached_Data and Shodan_Item_URL not in Data_to_Cache and Current_Step < int( self.Limit): Output_file = General.Create_Query_Results_Output_File( Directory, Query, Local_Plugin_Name, Shodan_Item_Response, Shodan_Item_Host, self.The_File_Extensions["Query"]) if Output_file: Output_Connections.Output( [Main_File, Output_file], Shodan_Item_URL, Title, self.Plugin_Name.lower()) Data_to_Cache.append( Shodan_Item_URL) else: logging.warning( f"{Common.Date()} - {self.Logging_Plugin_Name} - Failed to create output file. File may already exist." ) Current_Step += 1 elif self.Type == "Host": Local_Plugin_Name = self.Plugin_Name + "-Host" try: API_Response = API_Session.host(Query) except Exception as e: logging.error( f"{Common.Date()} - {self.Logging_Plugin_Name} - {str(e)}." ) break JSON_Output_Response = Common.JSON_Handler( API_Response).Dump_JSON() Main_File = General.Main_File_Create( Directory, Local_Plugin_Name, JSON_Output_Response, Query, self.The_File_Extensions["Main"]) Output_Connections = General.Connections( Query, Local_Plugin_Name, self.Domain, self.Result_Type, self.Task_ID, self.Plugin_Name.lower()) Shodan_URL = f"https://www.{self.Domain}/host/{Query}" Title = f"Shodan | {Query}" if Shodan_URL not in Cached_Data and Shodan_URL not in Data_to_Cache: Shodan_Responses = Common.Request_Handler( Shodan_URL, Application_JSON_CT=True, Accept_XML=True, Accept_Language_EN_US=True, Filter=True, Host=f"https://www.{self.Domain}") Shodan_Response = Shodan_Responses["Filtered"] Output_file = General.Create_Query_Results_Output_File( Directory, Query, self.Plugin_Name, Shodan_Response, Query, self.The_File_Extensions["Query"]) if Output_file: Output_Connections.Output( [Main_File, Output_file], Shodan_URL, Title, self.Plugin_Name.lower()) Data_to_Cache.append(Shodan_URL) else: logging.warning( f"{Common.Date()} - {self.Logging_Plugin_Name} - Failed to create output file. File may already exist." ) else: logging.warning( f"{Common.Date()} - {self.Logging_Plugin_Name} - No results found." ) except: logging.warning( f"{Common.Date()} - {self.Logging_Plugin_Name} - Failed to complete task." ) Cached_Data_Object.Write_Cache(Data_to_Cache) except Exception as e: logging.warning( f"{Common.Date()} - {self.Logging_Plugin_Name} - {str(e)}")
import urllib.request from shodan import Shodan SHODAN_API_KEY = "" # enter API Key here api = Shodan(SHODAN_API_KEY) ip = urllib.request.urlopen( 'http://www.networksecuritytoolkit.org/nst/tools/ip.php').read().decode( 'utf-8') # gets current IP address and parses print(ip) print(api.host( ip, minify=True)) #queries the Shodan db and outputs minified result
def host(self, ips, history=False, minify=False): host = Shodan.host(self, ips, history=history, minify=minify) if host: return host
def host(self, ips): host = Shodan.host(self, ips) if host: return host
# Whether or not to look up historical information for the IPs use_history = False if len(argv) == 4: use_history = True # Must have initialized the CLI before running this script key = get_api_key() # Create the API connection api = Shodan(key) # Create the output file fout = open_file(output_filename, 'w') # Open the file containing the list of IPs with open(input_filename, 'r') as fin: # Loop over all the IPs in the file for line in fin: ip = line.strip() # Remove any trailing whitespace/ newlines # Wrap the API calls to nicely skip IPs which don't have data try: print('Processing: {}'.format(ip)) info = api.host(ip, history=use_history) # All the banners are stored in the "data" property for banner in info['data']: write_banner(fout, banner) except: pass # No data