예제 #1
0
    def run(self, info):

        # This is where we'll collect the data we'll return.
        results = []

        # Skip unsupported IP addresses.
        if info.version != 4:
            return
        ip = info.address
        parsed = netaddr.IPAddress(ip)
        if parsed.is_loopback() or \
           parsed.is_private()  or \
           parsed.is_link_local():
            return

        # Query Shodan for this host.
        try:
            key = self.get_api_key()
            api = WebAPI(key)
            shodan = api.host(ip)
        except Exception, e:
            tb = traceback.format_exc()
            Logger.log_error("Error querying Shodan for host %s: %s" % (ip, str(e)))
            Logger.log_error_more_verbose(tb)
            return
예제 #2
0
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)
예제 #3
0
파일: dir300.py 프로젝트: 0x90/routerz
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)
예제 #4
0
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')
예제 #5
0
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
예제 #6
0
	def locateip(self, data):
		if '!locateip' in data['recv']:
			args = argv('!locateip',data['recv'])
			api = WebAPI("KpYC07EoGBtGarTFXCpjsspMVQ0a5Aus")#don look
			query = args['argv'][1]
			try:
				socket.inet_aton(query)
			except socket.error:
				return None
			results = api.host(query)
			output = []
			output.append('OS: ' + str(results['os']))
			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_name']) + '\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))
			ircoutput = ''
			for line in output:
				ircoutput += say(args['channel'],line)
			return ircoutput
예제 #7
0
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
예제 #8
0
파일: dir300.py 프로젝트: dot-Sean/routerz
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)
예제 #9
0
 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 = WebAPI(self.key)
예제 #10
0
파일: plugins.py 프로젝트: vladc/IRCLinkBot
 def locateip(self, data):
     if '!locateip' in data['recv']:
         args = argv('!locateip', data['recv'])
         api = WebAPI("KpYC07EoGBtGarTFXCpjsspMVQ0a5Aus")  #don look
         query = args['argv'][1]
         try:
             socket.inet_aton(query)
         except socket.error:
             return None
         results = api.host(query)
         output = []
         output.append('OS: ' + str(results['os']))
         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_name']) +
                       '\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))
         ircoutput = ''
         for line in output:
             ircoutput += say(args['channel'], line)
         return ircoutput
예제 #11
0
 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 = WebAPI(self.key)
예제 #12
0
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
예제 #14
0
    def __init__(self, host):
        self.host = host
        self.shodan_api_key = "oykKBEq2KRySU33OxizNkOir5PgHpMLv"

        if self.shodan_api_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 = WebAPI(self.shodan_api_key)
예제 #15
0
 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()
예제 #16
0
파일: ip.py 프로젝트: benhagen/dossier
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 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
예제 #18
0
	def __init__(self,host):
		self.host=host
		self.key = ""
		if self.api =="":
			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 = WebAPI(self.key)
예제 #19
0
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
예제 #20
0
	def __init__(self,host):
		self.host=host
		self.shodan_api_key = "oykKBEq2KRySU33OxizNkOir5PgHpMLv"

		if self.shodan_api_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 = WebAPI(self.shodan_api_key)
예제 #21
0
 def __init__(self, queue, tid, cli):
     threading.Thread.__init__(self)
     self.queue = queue
     self.tid = tid
     self.cli = cli
     self.bruteForcePorts = {'ftpBrute': 21, 'sshBrute': 22}
     if self.cli.useShodan == True:
         #Using Shodan to search information about this machine in shodan database.
         log.info(
             "[+] Shodan Activated. About to read the Development Key. ")
         if self.cli.shodanKey == None:
             #If the key is None, we can't use shodan.
             log.warn(
                 "[-] Shodan Key's File has not been specified. We can't use shodan without a valid key"
             )
         else:
             #Read the shodan key and create the WebAPI object.
             shodanKey = open(self.cli.shodanKey).readline().rstrip('\n')
             self.shodanApi = WebAPI(shodanKey)
             log.info("[+] Connected to Shodan. ")
예제 #22
0
    def __init__(self, search):

        #Attributes

        self.configFile = "config.dat"
        self.dataList = []
        self.resultsList = None
        self.API_KEY = ""
        self.loadData()
        self.API_KEY = self.dataList[0]
        self.search = search
        self.api = WebAPI(self.API_KEY)
예제 #23
0
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
예제 #24
0
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_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')
예제 #26
0
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
예제 #27
0
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
예제 #28
0
class search_shodan():
	def __init__(self,host):
		self.host=host
		self.key = ""
		if self.api =="":
			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 = WebAPI(self.key)
	def run(self):
		try:
			host = self.api.host(self.host)
			return host['data']
		except:
			#print "SHODAN empty reply or error in the call"
			return "error"
예제 #29
0
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
예제 #30
0
def main():
# Functional options:
# -s -> Just Search CarelDataServer hosts. Execution result is a text file with one host per line
# -sbf -> Search and BruteForce. Execution result is a text file with hosts and possible users/passwords in those hosts
# -bf -> Just BruteForce. Input file with one host per line. Execution result is an output text file with hosts and valid users/passwords
#
# Bruteforce methods:
# -sp -> Just Simple Passwords
# -da -> Dictionary Attack. Input file with one password per line
	
	func = raw_input('Select functionality (s/sbf/bf): ')
	while ((func != 's') and (func != 'sbf') and (func != 'bf')):
		func = raw_input('WRONG OPTION! Select functionality (s/sbf/bf): ')
	
	if ((func == 'sbf') or (func == 'bf')):
		bfm = raw_input('Select brute force method (sp/da): ')
		while ((bfm != 'sp') and (bfm != 'da')):
			func = raw_input('WRONG OPTION! Select brute force method (sp/da): ')
	
	servers = []
	
	outfile = raw_input('Output file name: ')
	if ((func == 's') or (func =='sbf')):
		SHODAN_API_KEY = raw_input('Shodan API key: ')
		api = WebAPI(SHODAN_API_KEY)
		servers_search(api, servers)
		if (func == 's'):
			of = open(outfile, 'w')
			for s in servers:
				s.print_ip(of)
			of.close()
	
	if ((func == 'sbf') or (func == 'bf')):
		if (func == 'bf'):
			inputfile = raw_input('Hosts file name: ')
			servers_load(inputfile, servers)

		if (bfm == 'da'):
			dictfile = raw_input('Dictionary file name: ')
		
		of = open(outfile, 'w')
		for s in servers:
			s.get_users()
			s.simple_passwords_attack()
			if (bfm == 'da'):
				s.dictionary_attack(dictfile)
			s.print_logins(of)
		of.close()
예제 #31
0
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 WebAPI
        self.api = WebAPI(self.plugin_config["api_key"])

    def get_info(self, arg):
        info = self.api.host(arg)
        return info
예제 #32
0
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 = WebAPI(self.key)

    def run(self):
        try:
            host = self.api.host(self.host)
            return host['data']
        except:
            #print "SHODAN empty reply or error in the call"
            return "error"
예제 #33
0
	def __init__(self, queue, tid, cli) :
		threading.Thread.__init__(self)
		self.queue = queue
		self.tid = tid
        	self.cli = cli
		self.bruteForcePorts ={'ftpBrute':21, 'sshBrute':22}
		if self.cli.useShodan == True:
			#Using Shodan to search information about this machine in shodan database.
			log.info("[+] Shodan Activated. About to read the Development Key. ")
			if self.cli.shodanKey == None:
				#If the key is None, we can't use shodan.
				log.warn("[-] Shodan Key's File has not been specified. We can't use shodan without a valid key")
			else:
				#Read the shodan key and create the WebAPI object.
				shodanKey = open(self.cli.shodanKey).readline().rstrip('\n')
				self.shodanApi = WebAPI(shodanKey)
				log.info("[+] Connected to Shodan. ")
예제 #34
0
class search_shodan():
    def __init__(self, host, key):
        self.host = host
        if key != "":
            self.key = key
        else:
            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 = WebAPI(self.key)

    def run(self):
        try:
            host = self.api.host(self.host)
            return host['data']
        except:
            print "SHODAN empty reply or error in the call"
            return "error"
예제 #35
0
파일: samurai.py 프로젝트: Hashdump/Samauri
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
예제 #36
0
파일: samurai.py 프로젝트: Hashdump/Samauri
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
예제 #37
0
파일: samurai.py 프로젝트: Hashdump/Samauri
#!/usr/bin/python
"""
To install 'easy_install shodan' to install
the shodan libraries
"""
from shodan import WebAPI

#My key. Get your own :)
KEY = ""
api = WebAPI(KEY)


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)
예제 #38
0
def checkCam(ip):
    try:
        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):
예제 #39
0
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']
예제 #40
0
#!/usr/bin/python
# What: Snippet to include Shodan input to an ETL process. Reads a list of IP addresses and generates a json file with Shodan's output.
# POC: [email protected] 
# License: Open Source Software - Apache2

from shodan import WebAPI
import json

SHODAN_API_KEY = "your api key"
infilename = "hosts.txt" # one ip per line
outfilename = "output.json"

shodan = WebAPI(SHODAN_API_KEY)

print "Reading hosts from ", infilename
print "Writing json to ", outfilename, "\n"

outfile = open(outfilename, 'w')
for line in open(infilename, 'r'):
    print "Looking up ", line
    host = shodan.host(line)
    outfile.write(json.dumps(host, indent=4))
outfile.close




예제 #41
0
'''
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
예제 #42
0
'''
Created on Feb 22, 2014

@author: Zhu Yirong
'''
from shodan import WebAPI

SHODAN_API_KEY = "CUn5UHoYD784Z3AlfUdvulRjiP2oUBfm"

api= WebAPI(SHODAN_API_KEY)

# This example retrieves detailed information from a list of hosts, and count how many of them are accessible.
count=0
for i in range(41,50):
    try:
        host = api.host('217.140.75.'+str(i))
        print 'accessing host %s' % host['ip']
        print '%s' % host # print the entire jasonobject for the host.
        count+=1

    except Exception, e:
        print 'Error: %s 217.140.75.%s' % (e,i)

print 'total # of available hosts in the range is %s' % count
예제 #43
0
#!/usr/bin/env python
#
# shodan plugin
#
# Author: Radek Domanski
# email: radek.domanski # gmail.com
# website: intothebug.com

from shodan import WebAPI
import sys

# put your shodan API key here
SHODAN_API_KEY = ""

api = WebAPI(SHODAN_API_KEY)

try:
    host = api.host(sys.argv[1])

    r = ''

    # process data from shodan
    for item in host['data']:
	for key in item.keys():
	    r += "%s: %s" % (key, repr(item[key]))
	r += "\n==============================\n"

    print r
except Exception, e:
    print "Error: %s" % e
예제 #44
0
 def __init__(self, API_KEY):
     self.api = WebAPI(API_KEY)
예제 #45
0
 def __init__(self,API_KEY):
     self.api =  WebAPI(API_KEY)    
예제 #46
0
파일: samurai.py 프로젝트: Hashdump/Samauri
 def __init__(self, KEY):
     self.api = WebAPI(KEY)
예제 #47
0
 def setup(self):
     from shodan import WebAPI
     self.api = WebAPI(self.plugin_config["api_key"])
예제 #48
0
FACET_TITLES = {
    'org': 'Top 10 Organizations',
    'domain': 'Top 10 Domains',
    'port': 'Top 10 Ports',
    'asn': 'Top 10 Autonomous Systems',
    'country': 'Top 5 Countries',
}

# Input validation
if len(sys.argv) == 1:
    print 'Usage: %s <search query>' % sys.argv[0]
    sys.exit(1)

try:
    # Setup the api
    api = WebAPI(SHODAN_API_KEY)

    # Generate a query string out of the command-line arguments
    query = ' '.join(sys.argv[1:])

    # Use the count() method because it doesn't return results and doesn't require a paid API plan
    # And it also runs faster than doing a search().
    result = api.count(query, facets=FACETS)

    print 'Shodan Summary Information'
    print 'Query: %s' % query
    print 'Total Results: %s\n' % result['total']

    # Print the summary info from the facets
    for facet in result['facets']:
        print FACET_TITLES[facet]
 def __initKey(self):
     self.api = WebAPI("CvXzhcMm3YemfeNnNKE7ed9xRSCKfAhY")
예제 #50
0
 def __init__(self, shodan_api_key):
     self.api_key = shodan_api_key
     self.api = WebAPI(self.api_key)
예제 #51
0
        verboseprint = lambda *a: None

    if not (args.query or args.host or args.exploit or args.in_file):
        parser.error("Not enough arguements given.")

    if (args.host or args.exploit) and (not args.api_key or args.xml_file):
        parser.error(
            "Exploit/Host lookups aren't locally supported and require a Shodan API Key."
        )

    if not args.xml_file and not args.api_key:
        parser.error("Shodan API key required to perform queries.")

    if args.api_key:
        verboseprint("key detected")
        api = WebAPI(args.api_key)
        verboseprint("webapi object created successfully")

    out_root = ET.Element("pydan")
    out_tree = ET.ElementTree(out_root)
    verboseprint("initialized empty xml tree for output")

    if args.xml_file and args.xml_file != "":
        verboseprint("input xml file detected")
        tree = ET.parse(xml_file)
        verboseprint("parsed xml file successfully")
        importXML(tree, out_tree)
        del tree

    if args.query:
        if args.xml_file:
예제 #52
0
#                         mirwan aka cassaprogy,shadow_maker,suddent_death,aip,r3d3,dawflin,n1nj4,hakz,
#                         leXel,s3my0n,MaXe,Andre Corleone ,Shamus,and all my friend .
#          thanks communty : Tecon-crew<[url]http://tecon-crew.org[/url]>
#                            Void-labs <[url]http://void-labs.org[/url]>
#                            Makassar ethical hacker<[url]http://makassarhacker.com/>[/url]
#                            Intern0t <[url]http://forum.intern0t.net/>[/url]
#                            Deadc0de <[url]http://forum.deadc0de.or.id/>[/url]
#-----------------------------------------------
import shodan, sys, time, base64, os
from time import sleep
from shodan import WebAPI

__author__ = 'amltbXlyb21hbnRpY2Rldmls'
__email__ = 'PHJvbWFudGljZGV2aWwuamltbXlAZ21haWwuY29tPg=='
__api__ = 'Z4xjUqqsaQbFgYrnn3EBuoJsSC0VZTyI'  #request youre api key  and paste in here
_lolz_ = WebAPI(__api__)


def tayping(title):
    try:
        for i in title:
            print "\b%s" % i,
            sys.stdout.flush()
            time.sleep(0.005)
    except ImportError:
        print "Some Error",


def check():
    try:
        checking = "[C]Checking module..."
예제 #53
0
			except :
			 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)	
예제 #54
0
#!/bin/python
# Author: Panderz
# Shodanhq search script

from shodan import WebAPI
import sys
import datetime

uniqdt = datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%M")

#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)
		
예제 #55
0
#!/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 "")
예제 #56
0
#!/usr/bin/env python
#
# shodan plugin
#
# Author: Radek Domanski
# email: radek.domanski # gmail.com
# website: intothebug.com

from shodan import WebAPI
import sys

# put your shodan API key here
SHODAN_API_KEY = ""

api = WebAPI(SHODAN_API_KEY)

try:
    host = api.host(sys.argv[1])

    r = ''

    # process data from shodan
    for item in host['data']:
        for key in item.keys():
            r += "%s: %s" % (key, repr(item[key]))
        r += "\n==============================\n"

    print r
except Exception, e:
    print "Error: %s" % e
예제 #57
0
class WorkerThread(threading.Thread):
	'''
	Worker Thread to information gathering and attack the exit nodes found.
	'''
	
	def __init__(self, queue, tid, cli) :
		threading.Thread.__init__(self)
		self.queue = queue
		self.tid = tid
        	self.cli = cli
		self.bruteForcePorts ={'ftpBrute':21, 'sshBrute':22}
		if self.cli.useShodan == True:
			#Using Shodan to search information about this machine in shodan database.
			log.info("[+] Shodan Activated. About to read the Development Key. ")
			if self.cli.shodanKey == None:
				#If the key is None, we can't use shodan.
				log.warn("[-] Shodan Key's File has not been specified. We can't use shodan without a valid key")
			else:
				#Read the shodan key and create the WebAPI object.
				shodanKey = open(self.cli.shodanKey).readline().rstrip('\n')
				self.shodanApi = WebAPI(shodanKey)
				log.info("[+] Connected to Shodan. ")
	def run(self) :
		lock = threading.Lock()
		while True :
			lock.acquire()
			host = None
			try:
				ip, port = self.queue.get(timeout=1)
				if hasattr(self, 'shodanApi'):
					log.info("[+] Using Shodan against %s " %(ip))
					try:
						shodanResults = self.shodanApi.host(ip)
						recordShodanResults(self, ip, shodanResults)
					except WebAPIError:
						log.error("[-] There's no information about %s in the Shodan Database." %(ip))
						pass
				
				if self.cli.brute == True:
					if self.cli.usersFile != None and self.cli.passFile != None:
						for method in self.bruteForcePorts.keys():
							if self.bruteForcePorts[method] == port:
								#Open port detected for a service supported in the "Brute-Forcer"
								#Calling the method using reflection.
								attr(service)
								
					else:
						log.warn("[-] BruteForce mode specified but there's no files for users and passwords. Use -u and -f options")
			except Queue.Empty :
				log.info("Worker %d exiting... "%self.tid)
			finally:
				log.info("Releasing the Lock in the Thread %d "%self.tid)
				lock.release()
				self.queue.task_done()
	
	def ftpBrute(self):
		log.info("Starting FTP BruteForce mode on Thread: %d "%self.tid)
		#log.info("Reading the Users File: %s "%self.cli.)
		
	def sshBrute(self):
		log.info("Starting SSH BruteForce mode on Thread: %d "%self.tid)
	
	def recordShodanResults(self, host, results):
		entryFile = 'shodanScan-%s.txt' %(host)
		shodanFileResults = open(entryFile, 'a')
		entry = '------- SHODAN REPORT START FOR %s ------- \n' %(host)
		recursiveInfo(entry, results)		
		entry = '------- SHODAN REPORT END FOR %s ------- \n' %(host)
		shodanFileResults.write(entry)
		shodanFileResults.close()			

	def recursiveInfo(self, entry, data):
		if type(data) == dict:
			for key in results.keys():
				if type(key) == dict:
					entry += recursiveInfo(entry, key)
				elif type(key) == list:
					for element in key:
						if type(key) == dict:
							entry += recursiveInfo(entry, key)
											
				else:
					entry += '[+]%s : %s \n' %(key, results[key])
					print entry