def shodan_search(search, apikey, pages): from shodan import WebAPI if apikey: API_KEY = apikey else: API_KEY = 'ENTER YOUR API KEY HERE AND KEEP THE QUOTES' api = WebAPI(API_KEY) ips_found = [] try: results = api.search(search, page=1) total_results = results['total'] print '[+] Results: %d' % total_results print '[*] Page 1...' pages = max_pages(pages, total_results) for r in results['matches']: ips_found.append(r['ip']) if pages > 1: i = 2 while i <= pages: results = api.search(search, page=i) print '[*] Page %d...' % i for r in results['matches']: ips_found.append(r['ip']) i += 1 return ips_found except Exception as e: print '[!] Shodan search error:', e
def autoroot(api_key, thread_count=10): api = WebAPI(api_key) search_queries = ['Server: Linux, HTTP/1.1, DIR','Mathopd/1.5p6' ]#, 'Server: Linux, HTTP/1.1, DIR-300'] for query in search_queries: count = 0 page = 1 total = 0 while True: results = api.search(query) if total == 0: total = int(results['total']) print('Results found: %s' % results['total']) print('Countries found: ') pprint(results['countries']) raw_input('press enter to start hacking') dm = DlinkManager(results['matches'],thread_count=10) dm.run() page += 1 count += len(results['matches']) if count == total: break print("Rooted routers count: %i" % len(rooted)) print(rooted)
class ShodanWorker(RedisWorker): qinput = Queue('search:shodan') def __init__(self, shodan_api_key=None, *args, **kwargs): super(ShodanWorker, self).__init__(*args, **kwargs) if not shodan_api_key: # We should do more to find this key shodan_api_key = os.environ.get('SHODAN_API_KEY') if not shodan_api_key: raise Exception('Shodan API key required') # FIXME self.api = WebAPI(shodan_api_key) self.nmap_worker = NmapWorker() def run(self, job): print 'JOB!', job query, page = job res = self.api.search(query, page=page)['matches'] for host in res: self.nmap_worker.add_job(host['ip'], host['port']) def query(self, query, page=1): self.qinput.send([query, page]) def count(self, query): return self.api.count(query)
class Shodan: """ Clase para buscar en Shodan """ def __init__(self, API_KEY): self.api = WebAPI(API_KEY) def buscar(self, cadena): """ Busca segun la cadena dada """ try: # Buscamos lo de la cadena pasada como parametro resultado = self.api.search(str(cadena)) return resultado except Exception as e: print 'Ups! Ha ocurrido un error: %s' % e resultado = [] return resultado def obtener_info_host(self, IP): """ Obtiene la info que pueda tener shodan sobre una IP """ try: host = self.api.host(IP) return host except Exception as e: print 'Ups! Ha ocurrido un error: %s' % e host = [] return host
def autoroot(api_key, thread_count=10): api = WebAPI(api_key) search_queries = ['Server: Linux, HTTP/1.1, DIR', 'Mathopd/1.5p6'] #, 'Server: Linux, HTTP/1.1, DIR-300'] for query in search_queries: count = 0 page = 1 total = 0 while True: results = api.search(query) if total == 0: total = int(results['total']) print('Results found: %s' % results['total']) print('Countries found: ') pprint(results['countries']) raw_input('press enter to start hacking') dm = DlinkManager(results['matches'], thread_count=10) dm.run() page += 1 count += len(results['matches']) if count == total: break print("Rooted routers count: %i" % len(rooted)) print(rooted)
def shodan_frame(port): # Currently Supports query based on port Filter only and Displays Corresponding IP print colored( "\n[!] Shodan Search Module For NoSQL Framework Launched.....", 'yellow') api = WebAPI("API KEY GOES HERE") if port == 5984: query = '{"couchdb":"Welcome","version":""}' else: query = 'port:%s' % (port) result = api.search(query) print colored("[-] Would Like to write the Results to a File", 'green') choice = raw_input() if choice.lower() == 'y': file = open('shodan-%s.txt' % (port), 'w') for host in result['matches']: file.write(host['ip'] + "\n") print colored('[-] File to %s/shodan-%s.txt' % (os.getcwd(), port), 'green') file.close() else: print colored("[-] Printing Found IP \n", 'blue') for host in result['matches']: print colored("[-] " + host['ip'], 'green')
class Shodan: """ Clase para buscar en Shodan """ def __init__(self,API_KEY): self.api = WebAPI(API_KEY) def buscar(self,cadena): """ Busca segun la cadena dada """ try: # Buscamos lo de la cadena pasada como parametro resultado = self.api.search(str(cadena)) return resultado except Exception as e: print 'Ups! Ha ocurrido un error: %s' % e resultado = [] return resultado def obtener_info_host(self,IP): """ Obtiene la info que pueda tener shodan sobre una IP """ try: host = self.api.host(IP) return host except Exception as e: print 'Ups! Ha ocurrido un error: %s' % e host = [] return host
class fingershodan: def __init__(self, search, typeSearch): self.search = search self.typeSearch = typeSearch self.searchList = {} self.allCount = 0 self.__initKey() self.__switchSearch() def __initKey(self): self.api = WebAPI("CvXzhcMm3YemfeNnNKE7ed9xRSCKfAhY") def __switchSearch(self): if self.typeSearch == "search": self.__execSearch() elif self.typeSearch == "lookup": self.search = socket.gethostbyname(self.search) self.webHost = self.api.host(self.search) self.__execLookup() #elif self.typeSearch=="mac": # self.__macLocation() def __execSearch(self): searched = self.api.search(self.search) for search in searched["matches"]: try: self.searchList["Result " + str(self.allCount)] = { "Ip": search["ip"], "Updated": search["updated"], "Country": search["country_name"], "Latitude": search["latitude"], "Longitude": search["longitude"], "Port": search["port"], "Data": search["data"], "Os": search["os"] } self.allCount += 1 except: continue def __execLookup(self): try: self.searchList["Result " + str(self.allCount)] = { "Ip": self.webHost["ip"], "Country": self.webHost["country_name"], "City": self.webHost["city"], "Os": self.webHost["os"], "Banner": self.webHost["data"][0]["banner"], "Port": self.webHost["data"][0]["port"], "TimeStamp": self.webHost["data"][0]["timestamp"] } except: print "Fail Lookup" #def __macLocation(self): def _returnData(self): return self.searchList
def shodan_search(search, apikey, pages): from shodan import WebAPI if apikey: API_KEY = apikey else: API_KEY = 'ENTER YOUR API KEY HERE AND KEEP THE QUOTES' api = WebAPI(API_KEY) ips_found = [] try: results = api.search(search, page=1) total_results = results['total'] print '[+] Results: %d' % total_results print '[*] Page 1...' pages = max_pages(pages, total_results) for r in results['matches']: # Replace the following ports with port 80 since they'll virtually never have a web server running # ftp, ssh, telnet, smtp, smtp, netbios x3, smb if r['port'] in [21, 22, 23, 25, 26, 137, 138, 139, 445]: r['port'] = 80 ips_found.append('%s:%s' % (r['ip'], r['port'])) if pages > 1: i = 2 while i <= pages: results = api.search(search, page=i) print '[*] Page %d...' % i for r in results['matches']: ips_found.append(r['ip']) i += 1 return ips_found except Exception as e: print '[!] Shodan search error:', e
def shodan_search(search, apikey, pages): from shodan import WebAPI if apikey: API_KEY = apikey else: API_KEY = "ENTER YOUR API KEY HERE AND KEEP THE QUOTES" api = WebAPI(API_KEY) ips_found = [] try: results = api.search(search, page=1) total_results = results["total"] print "[+] Results: %d" % total_results print "[*] Page 1..." pages = max_pages(pages, total_results) for r in results["matches"]: # Replace the following ports with port 80 since they'll virtually never have a web server running # ftp, ssh, telnet, smtp, smtp, netbios x3, smb if r["port"] in [21, 22, 23, 25, 26, 137, 138, 139, 445]: r["port"] = 80 ips_found.append("%s:%s" % (r["ip"], r["port"])) if pages > 1: i = 2 while i <= pages: results = api.search(search, page=i) print "[*] Page %d..." % i for r in results["matches"]: ips_found.append(r["ip"]) i += 1 return ips_found except Exception as e: print "[!] Shodan search error:", e
def main(queue): # Connect to Shodan api = WebAPI(API_KEY) # get the first page of results res = api.search(filter) #keep track of how many results we have left #total_results = res['total'] total_results = res.get('total', 0) # Start looping through results now page = 1 try: while(page * 100 <= total_results): #check the matches to see if they fit what we are looking for for host in res['matches']: queue.put_nowait(host['ip']) page +=1 res = api.search(filter,page) except Exception, e: print e
def shodanquery(query, api_key=None): if not api_key or api_key == "": return False api = WebAPI(api_key) if is_valid_ipv4(query): try: response = api.host(query) except: return False else: try: response = api.search(query) except: return False return response
class CamScanner(object): filter = "netcam" def __init__(self, shodan_api_key): self.api_key = shodan_api_key self.api = WebAPI(self.api_key) def cam_available(self, url): try: resp = urlopen(url, None, 10) except (URLError, timeout): print "Failed to contact cam: %s" % url return False else: if resp.code == 200: return True print "Bad resp code: %d" % resp.code return False def get_cams(self): results = self.api.search(self.filter) total_pages = (results["total"] / 50) + 1 current_page = 1 skip = False while current_page <= total_pages: if not skip: for result in results["matches"]: url = "http://%s/anony/mjpg.cgi" % result["ip"] if self.cam_available(url): yield url, result.get("latitude"), result.get("latitude") current_page += 1 try: results = self.api.search(self.filter, page=current_page) except URLError: print "Failed to GET page %d" % current_page skip = True
def shodan_search(search, apikey, pages): from shodan import WebAPI if apikey: API_KEY = apikey else: API_KEY = 'ENTER YOUR API KEY HERE AND KEEP THE QUOTES' api = WebAPI(API_KEY) ips_found = [] try: results = api.search(search, page=1) total_results = results['total'] print '[+] Results: %d' % total_results print '[*] Page 1...' pages = max_pages(pages, total_results) for r in results['matches']: full_ip = '%s:%s' % (r['ip'], r['port']) ips_found.append(full_ip) if pages > 1: i = 2 while i <= pages: results = api.search(search, page=i) print '[*] Page %d...' % i for r in results['matches']: full_ip = '%s:%s' % (r['ip'], r['port']) ips_found.append(full_ip) i += 1 return ips_found except Exception as e: print '[!] Shodan search error:', e
class fingershodan: def __init__(self,search,typeSearch): self.search = search self.typeSearch = typeSearch self.searchList = {} self.allCount = 0 self.__initKey() self.__switchSearch() def __initKey(self): self.api = WebAPI("CvXzhcMm3YemfeNnNKE7ed9xRSCKfAhY") def __switchSearch(self): if self.typeSearch=="search": self.__execSearch() elif self.typeSearch=="lookup": self.search = socket.gethostbyname(self.search) self.webHost = self.api.host(self.search) self.__execLookup() #elif self.typeSearch=="mac": # self.__macLocation() def __execSearch(self): searched = self.api.search(self.search) for search in searched["matches"]: try: self.searchList["Result "+str(self.allCount)] = {"Ip":search["ip"],"Updated":search["updated"], "Country":search["country_name"],"Latitude":search["latitude"],"Longitude":search["longitude"], "Port":search["port"],"Data":search["data"],"Os":search["os"]} self.allCount += 1 except: continue def __execLookup(self): try: self.searchList["Result "+str(self.allCount)] = {"Ip":self.webHost["ip"],"Country":self.webHost["country_name"],"City":self.webHost["city"], "Os":self.webHost["os"],"Banner":self.webHost["data"][0]["banner"],"Port":self.webHost["data"][0]["port"], "TimeStamp":self.webHost["data"][0]["timestamp"]} except: print "Fail Lookup" #def __macLocation(self): def _returnData(self): return self.searchList
def shodan_search(search, apikey): if apikey: API_KEY = args.apikey else: API_KEY = 'ENTER YOUR API KEY HERE AND KEEP THE QUOTES' api = WebAPI(API_KEY) ips_found = [] try: results = api.search('%s' % search) print '[+] Results: %s' % results['total'] for r in results['matches']: ips_found.append(r['ip']) return ips_found except Exception as e: print '[!] Error:', e
class ShodanScanner(object): def __init__(self, KEY): self.api = WebAPI(KEY) def searchShodan(self, search_string): try: filename = 'ips.txt' fp = open(filename, 'w'); self.results = self.api.search(search_string) for result in self.results['matches']: print result['ip'], str(result['latitude']), str(result['longitude']) fp.write(result['ip']+' '+str(result['latitude'])+','+str(result['longitude'])+'\n') for name in result['hostnames']: print name print result['data'] print '***%s results with \"%s\"***' % (self.results['total'], search_string) fp.close() except Exception, e: print 'Error: %s' % e
class ShodanScanner(object): def __init__(self, KEY): self.api = WebAPI(KEY) def searchShodan(self, search_string): try: filename = 'ips.txt' fp = open(filename, 'w') self.results = self.api.search(search_string) for result in self.results['matches']: print result['ip'], str(result['latitude']), str( result['longitude']) fp.write(result['ip'] + ' ' + str(result['latitude']) + ',' + str(result['longitude']) + '\n') for name in result['hostnames']: print name print result['data'] print '***%s results with \"%s\"***' % (self.results['total'], search_string) fp.close() except Exception, e: print 'Error: %s' % e
def shodan_frame(port): # Currently Supports query based on port Filter only and Displays Corresponding IP print colored("\n[!] Shodan Search Module For NoSQL Framework Launched.....",'yellow') api = WebAPI("API KEY GOES HERE") if port == 5984: query='{"couchdb":"Welcome","version":""}' else: query='port:%s'%(port) result = api.search(query) print colored("[-] Would Like to write the Results to a File",'green') choice=raw_input() if choice.lower()=='y': file=open('shodan-%s.txt'%(port),'w') for host in result['matches']: file.write(host['ip']+"\n") print colored('[-] File to %s/shodan-%s.txt'%(os.getcwd(),port),'green') file.close() else: print colored("[-] Printing Found IP \n",'blue') for host in result['matches']: print colored("[-] "+host['ip'],'green')
print " / _____/| |__\______ \___.__." print " \_____ \ | | \| ___< | |" print " / \| Y \ | \___ |" print "/_______ /|___| /____| / ____|" print " \/ \/ \/ " print "" print "# search_shodan.py #" print "# Search SHODAN and print a list of IPs matching the query #" print "# gunma, gunma.rootedker.nl #" print "" # Input validation if len(sys.argv) == 1: print 'Usage: %s <search query, eg. "netgear">' % sys.argv[0] sys.exit(1) # Wrap the request in a try/ except block to catch errors try: # Search Shodan results = api.search(' '.join(sys.argv[1:])) # Show the results print 'Results found: %s' % results['total'] for result in results['matches']: print 'IP: %s' % result['ip'] print result['data'] print '' except Exception, e: print 'Error: %s' % e
''' Created on Feb 22, 2014 @author: Zhu Yirong ''' from shodan import WebAPI SHODAN_API_KEY = "CUn5UHoYD784Z3AlfUdvulRjiP2oUBfm" api= WebAPI(SHODAN_API_KEY) # Wrap the request in a try/ except block to catch errors try: # Search Shodan results = api.search('apache') print results # Show the results for result in results['matches']: if '200 OK' in result['data']: print 'IP: %s' % result['ip'] except Exception, e: print 'Error: %s' % e
print "Error in listing " +site finally: lock.release() #print "Finished logging into ftp site %s"%site self.queue.task_done() queue = Queue.Queue() #sites = ["rtfm.mit.edu", "ftp.ncsa.uiuc.edu", "prep.ai.mit.edu", "gatekeeper.dec.com"] shodanKey = open('shodanKey').readline().rstrip('\n') api = WebAPI(shodanKey) results = api.search("port:21 anonymous") sites=results['ip'] threads = [] for i in range(4) : print "Creating WorkerThread : %d"%i worker = WorkerThread(queue, i) worker.setDaemon(True) worker.start() threads.append(worker) print "WorkerThread %d Created!"%i for site in sites : queue.put(site) queue.join()
hoststring = str(ip) + ":" + str(port) print 'Found http://%s/videostream.cgi' % hoststring f = '<img src="http://%s/videostream.cgi?user=admin&pwd=" height=240 width=320>\n' % hoststring outfile.write(f) outfile.flush() #file.close() return True return False except: return False api = WebAPI(key) #get the first page of results res = api.search(filter) #keep track of how many results we have left total_results = (res['total']) page = 1 list = [] outfile = open('netwave.html','w') length = 0 try: while(page * 100 <= total_results): # Check the matches to see if they fit what we are looking for for host in res['matches']: ip = ''.join(str(host['ip'])) port = ''.join(str(host['port'])) pool.apply_async(checkCam, (ip,port),) #pool.join()
workbook = xlsxwriter.Workbook('VulnerableLocation.xlsx') worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': True}) worksheet.write('A1','IP',bold) worksheet.write('B1','Latitude',bold) worksheet.write('C1','Longitude',bold) worksheet.write('D1','Country',bold) worksheet.write('E1','Port',bold) row = 1 try: # Search Shodan results = api.search('port:32764') # Show the results print results for result in results['matches']: ipaddress = result['ip'] latitude = result['latitude'] longitude = str(result['longitude']) country = result['country_name'] port = result['port'] worksheet.write(row, 0, ipaddress) worksheet.write(row, 1, latitude) worksheet.write(row, 2, longitude) worksheet.write(row, 3, country) worksheet.write(row, 4, port)
## shodan ## ## https://pypi.python.org/pypi/shodan ## download ... extract ## python setup.py install ## if __name__ == '__main__': import os import re from shodan import WebAPI SHODAN_API_KEY = "API-KEY-HERE" api = WebAPI(SHODAN_API_KEY) info = {} path = os.path.join(os.getcwd(), 'data', 'hosts.txt') with open(path, 'r') as f: for line in f: l = line.strip() results = api.search(l) for r in results['matches']: for m in r['data'].split('\n'): match = re.match('^Server: (.*)$', m) if match: ## ## <ip>:<server striing> ## print '%s:%s'%(r['ip'], match.group(1))
#!/usr/bin/env python ''' Faraday Penetration Test IDE - Community Version Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) See the file 'doc/LICENSE' for the license information ''' from shodan import WebAPI import xmlrpclib SHODAN_API_KEY = "insert your API key here" api = WebAPI(SHODAN_API_KEY) # Wrap the request in a try/ except block to catch errors try: # Search Shodan print "Search Shodan" results = api.search('apache') #Connect to faraday print "Connecting Farday" api = xmlrpclib.ServerProxy("http://127.0.0.1:9876/") # Show the results print 'Results found: %s' % results['total'] for result in results['matches']: if "ip" in result: print 'IP: %s' % result['ip'] print result['data'] print '' h_id = api.createAndAddHost( result['ip'], result['os'] if result['os'] is not None else "")
#Define your key here SHODAN_API_KEY = "" api = WebAPI(SHODAN_API_KEY) userdef = raw_input ("What do you want to look for: ") print ("Searching the Internets! ") class fileout(object): def __init__(self, filename="search.txt"): self.terminal = sys.stdout self.log = open(filename, "a") def write(self, message): self.terminal.write(message) self.log.write(message) sys.stdout = fileout("shosearch" + uniqdt + ".txt") try: results = api.search(userdef) print 'Results found: %s' % results['total'] for result in results['matches']: print 'IP: %s' % result['ip'] print result['data'] print '' except Exception, e: print 'Error: %s' % e
from shodan import WebAPI SHODAN_API_KEY = "" api = WebAPI(SHODAN_API_KEY) # This example search a specific keyword in Shodan databae, and print the results. try: # Search Shodan #results = api.search('web camera') results = api.search('webcam -www-authenticate +last-modified') print results import csv writer= csv.writer(open("./data/extra/webcam.csv", "wb")) #orig_stdout =sys.stdout f = file('out.txt', 'w') writer.writerow(['City','Country Name', 'IP', 'latitude', 'Longitude','Country Code', 'ISP', 'Organization']) print 'City',',','Country Name',',', 'IP',',', 'latitude',',', 'Longitude',',','Country Code',',', 'ISP',',', 'Organization' for result in results['matches']: #print 'IP: %s' % result['ip'] #print result['data'] print result #writer.writerow(result['ip']) writer.writerow([result['city'],result['country_name'], result['ip'], result['latitude'], result['longitude'], result['country_code'], result['isp'], result['org']]) #print api.host(result['ip']) #print str(tuple([str(e) for e in result])) #print str(tuple(map(str, result))) #print result['city'] ,',', result['country_name'],',', result['ip'],',',result['latitude'],',',result['longitude'],',',result['country_code3'],',',result['isp'],',',result['org']
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1.5) sock.connect((ip, 80)) sock.send('GET /anony/mjpg.cgi HTTP/1.0\r\n\r\n') res = sock.recv(100) if (res.find('200 OK') > 0): return True return False except: return False api = WebAPI(key) #get the first page of results res = api.search(filter) #keep track of how many results we have left total_pages = (res['total'] / 50) + 1 page = 1 outfile = open('camlog_new', 'w') try: while (page <= total_pages): #check the matches to see if they fit what we are looking for for r in res['matches']: #if(r['data'].find(filter)>0): print 'Checking %s' % r['ip'] if (checkCam(r['ip'])): print 'Found http://%s/anony/mjpg.cgi' % r['ip']
if(res.find('200 Ok') > 0): return True return False except: return False if __name__ == "__main__": api = WebAPI(key) res = api.search('DSL Router micro_httpd')#Dork shodan dos modelos vulneraveis i = 1 try: while i <= 100: #Vai printar apenas 100 resultados pela API ser free for ips in res['matches']: print '[!] Testando http://%s' % ips['ip'] + bcolors.WARNING +' | Localizado em: ' + bcolors.ENDC + ips['country_name'] + bcolors.WARNING + ' | na porta:'+ bcolors.ENDC, bcolors.OKBLUE, ips['port'], bcolors.ENDC if(checar(ips['ip'])): print '[+] Is vull: http://%s/password.cgi' % ips['ip'] i +=1 except(): print 'Failed'