示例#1
0
 def __init__(self):
     self.key = shodanAPI_key
     if self.key == '':
         raise MissingKey(True)
     self.api = Shodan(self.key)
     self.hostdatarow = []
示例#2
0
 def __getShodanByAPI__(self, shodan_api='', session_id=None):
     if not shodan_api:
         return Shodan(ht.Config.getAPIKey('shodan_api', session_id))
     return Shodan(shodan_api)
示例#3
0
from sys import argv, exit

# Input validation
if len(argv) != 3:
    print('Usage: {} <IPs filename> <output.json.gz>'.format(argv[0]))
    print('Example: {} iplist.txt iplist.json.gz'.format(argv[0]))
    exit(1)

input_filename = argv[1]
output_filename = argv[2]

# Must have initialized the CLI before running this script
key = get_api_key()

# Create the API connection
api = Shodan(key)

# Create the output file
fout = open_file(output_filename, 'w')

# Open the file containing the list of IPs
with open(input_filename, 'r') as fin:
    # Loop over all the IPs in the file
    for line in fin:
        ip = line.strip()  # Remove any trailing whitespace/ newlines

        # Wrap the API calls to nicely skip IPs which don't have data
        try:
            print('Processing: {}'.format(ip))
            info = api.host(ip)
    sys.stdout.write('%s[+] load favicon source: %s%s\n' %
                     (fg('green'), favsource, attr(0)))
    sys.stdout.write('[+] favicon size: %d\n' % len(data))

if not len(data):
    if not args.silent:
        sys.stdout.write('%s[-] invalid favicon%s\n' % (fg('red'), attr(0)))
    exit()

favhash = faviconHash(data, web_src)
if not args.silent:
    sys.stdout.write('%s[+] hash calculated: %s%s\n' %
                     (fg('green'), str(favhash), attr(0)))

if shokey:
    shodan = Shodan(shokey)
    search = 'http.favicon.hash:' + str(favhash)
    if not args.silent:
        sys.stdout.write('[+] searching: %s\n' % search)
    t_results = shodan.search(search)
    if not args.silent:
        sys.stdout.write('%s[+] %d results found%s\n' %
                         (fg('green'), len(t_results['matches']), attr(0)))
    for result in t_results['matches']:
        tmp = []
        for v in t_values:
            if v in result:
                tmp.append(str(result[v]))
            else:
                tmp.append('')
        # print( tmp )
示例#5
0
def init():
    # set API key
    api_key = "PUT YOUR SHODAN API LEY HERE"
    # define and init global API object
    global api
    api = Shodan(api_key)
示例#6
0
from shodan import Shodan
import requests
import subprocess

IP = ""
api = Shodan('')

def url_ok(url):
    r = requests.head("http://" + url)
    return r.status_code == 200

def check_page(url):
    r = requests.get("http://" + url + "/admin/")
    return "Pi-hole" in r.text

def pruneIPS(vulnerableIPs):
    for i in vulnerableIPs:
        if not url_ok(i):
            if not check_page(i):
                vulnerableIPs.remove(i)
    return vulnerableIPs

result = api.search("pi-hole")

VulnerableIP = []
for service in result['matches']:
    if service['ip_str'] == IP:
       ulnerableIP.append(service['ip_str'])
        print("Yes")
示例#7
0
    # output file name
    parser.add_argument('--out', help='json output file path')

    args = parser.parse_args()

    got_api = False
    default_config_path = os.path.abspath(
        str(os.path.dirname(os.path.realpath(__file__))) +
        "/../conf/shodan.conf")

    if args.config:
        config.read(args.config)

        if config['Shodan']["api_key"] != "API KEY HERE":
            api = Shodan(config['Shodan']["api_key"])
            got_api = True

    elif args.key:
        api = Shodan(args.key)
        got_api = True

    else:
        config.read(default_config_path)

        if config['Shodan']["api_key"] != "API KEY HERE":

            api = Shodan(config['Shodan']["api_key"])
            got_api = True

    print(" ")
        parse_response(host)
    except APIError, e:
        if e.value == "Invalid IP":
            print "[!] Invalid IP format"
        else:
            print "[!] Unkown error (\"%s\")" % (e.value)


#####################
# Main starts here
#####################
if __name__ == "__main__":
    check_api()

    parser, args = parse_args()
    api = Shodan(API_KEY)

    VERBOSE = args.verbose
    if args.time:
        time = int(args.time) if args.time.isdigit() else 0

    # Do main work
    try:
        if (args.ip):
            query(args.ip)
        elif (args.file):
            print "[!] Waiting %d seconds between each query" % (time)
            for e in read_file_into_list(args.file):
                query(e)
                sleep(time)
        else:
示例#9
0
    def initShodan(self, key):

        with open('shodan_api_key', 'w') as file:
            file.write(key)

        self.api = Shodan(key)
示例#10
0
import json
import dateutil.parser as dp
import schedule                                 #pip install schedule
from cStringIO import StringIO
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email import Charset
from email.generator import Generator
import smtplib
import ast

conn = sqlite3.connect('shodan_db.sqlite')

# Create a connection to the Shodan API
api = Shodan(SHODAN_API_KEY)

#Queries Shodan for a search term and then stores results in a list of dictionaries
def query_Shodan(term, callback):
    print "Runing Shodan Query"
    templist = []
    previous_ip=""
    while True:
        try:
            #Search Shodan and get bunch of IP Addresses (limit 100, you can increase it even more as per the number of servers you are planning to monitor)
            results = api.search(term,page=1,limit=100)
            #Construct a temp dictionary to store details of each of IP Address
            
            for result in results['matches']:

                #Shodan repeat IP entries for each port Open on an IP, the below code is for that
示例#11
0
from shodan import Shodan

api = Shodan('QoN9YkJiB2w5o6AjYXaeXFxRIYocUCPX')


def ipscan():
    ip = raw_input("enter an ip address")

    host = api.host(ip)

    print("""
            IP:                      {}
            Organization:            {}
            City                     {}
            Operating System:        {}
            Hostnames:               {}
            Country:                 {}
            Updated:                 {}
            Number of open ports      {}
    """.format(host['ip_str'], host.get('org', 'n/a'), host.get('city', 'n/a'),
               host.get('os', 'n/a'), " ".join(host.get('hostnames')),
               host.get('country_name'), host.get('last_update'),
               len(host.get('ports'))))

    for item in host['data']:
        print("""Port: {} / {}            Product: {} """.format(
            item['port'], item['transport'], item.get('product', 'n/a')))


def myip():
    print(api.tools.myip())
示例#12
0
    def send_command(self, command, search, thread_num, exec_cmd, startIP, endIP, ipfile):
        """Execute a command"""
        if search == "censys":
            self.search = Censys()
        elif search == "zoomeye":
            self.search = Zoomeye()
        elif search == "shodan":
            self.search = Shodan()
        elif search == "local":
            self.search = Local()
        else:
            print "you got a wrong type of search engine, you can select censys, shodan or zoomeye as your scan engine."
            sys.exit()
        
        if self.setQuery(command):
            return {'prompt': '', 'busy': False, 'data': 'QUERY => %s\n' % self.query}
        elif self.setPage(command):
            return {'prompt': '', 'busy': False, 'data': 'PAGE => %d\n' % self.page}
        else:
            if command == "exploit\n" or command == "run\n":
                if not self.search:
                    print "please select a search engine using the -s or --search option."
                    sys.exit()
                
                if (self.module and self.moduleType) or exec_cmd:
                    if (startIP and endIP) or ipfile:
                        args = (self.queue, self.STOP_ME, startIP, endIP, ipfile)
                    else:
                        if self.query:
                            self.search.getConfig()
                            args = (self.query, self.page, self.queue, self.STOP_ME)
                        else:
                            return {'prompt': '', 'busy': False, 'data': 'QUERY must be setted\n'}
                    threads = []
                    t1 = threading.Thread(target = self.search.searchIP, args = args)
                    threads.append(t1)
                    t2 = threading.Thread(target=self.DoExploit, args=(exec_cmd, command, thread_num))
                    threads.append(t2)
                    for t in threads:
                        t.setDaemon(True)
                        t.start()

                    for t in threads:
                        t.join()
                    
                    result = {'prompt': '', 'busy': False, 'data': '\n'}
                else:
                    return {'prompt': '', 'busy': False, 'data': 'please select the module\n'}
            else:
                isSuccess = self.client.call('console.write', [self.console_id, command])
                if isSuccess.has_key('error'):
                    self.login()
                    self.client.call('console.write', [self.console_id, command])
                sleep(0.5)
                result = self.client.call('console.read', [self.console_id])
                while result['busy']:
                    if result['data']:
                        print result['data']
                    sleep(0.5)
                    result = self.client.call('console.read', [self.console_id])
                
                if command == "show options\n":
                    if exec_cmd:
                        result['data'] = "%s   command              %s\n" % (result['data'], exec_cmd)
                    result['data'] = "%s   QUERY             %s\n" % (result['data'], self.query)
                    result['data'] = "%s   PAGE              %s\n" % (result['data'], self.page)

                if command.startswith("use"):
                    module = command.split(' ')[1].strip()
                    self.moduleType = module[:module.find('/')]
                    self.module = module[module.find('/')+1:]

                if command.startswith("set"):
                    options = command.split(' ')
                    self.opts[options[1]] = options[2].strip()
            
            return result
def main(api_key, search):
    api = Shodan(api_key)

    for result in api.search_cursor(search):
        print(result['hostnames'])
示例#14
0
from shodan import Shodan
from pathlib import Path
import configparser
import requests
from CloudCarrot.settings import __config_file__
import os

config = configparser.ConfigParser()
try:
    config.read(os.path.join(str(Path.home()),
                             '.config/{}'.format(__config_file__)))
    TOKEN = config.get('shodan', 'API_KEY')
except configparser.NoSectionError:
    TOKEN = False

api = Shodan(TOKEN)


def shodan_search(host):
    if not TOKEN:
        return False
    try:
        banner = api.search_cursor('"{0}"'.format(host))
        title_result = set([host['ip_str'] for host in banner])
        if title_result:
            return title_result
        else:
            return set()
    except:
        return False
示例#15
0
def shodan_search_worker(fk,
                         query,
                         search_type,
                         category,
                         country=None,
                         coordinates=None,
                         all_results=False):
    results = True
    page = 1
    SHODAN_API_KEY = keys['keys']['shodan']
    pages = 0
    screenshot = ""
    print(query)

    while results:
        if pages == page:
            results = False
            break

        # Shodan sometimes fails with no reason, sleeping when it happens and it prevents rate limitation
        search = Search.objects.get(id=fk)
        api = Shodan(SHODAN_API_KEY)
        fail = 0

        try:
            time.sleep(5)
            if coordinates:
                results = api.search("geo:" + coordinates + ",20 " + query,
                                     page)
            if country:
                results = api.search("country:" + country + " " + query, page)
        except:
            fail = 1
            print('fail1, sleeping...')

        if fail == 1:
            try:
                time.sleep(10)
                if coordinates:
                    results = api.search("geo:" + coordinates + ",20 " + query,
                                         page)
                if country:
                    results = api.search("country:" + country + " " + query,
                                         page)
            except Exception as e:
                print(e)

        if fail == 1:
            try:
                time.sleep(10)
                if coordinates:
                    results = api.search("geo:" + coordinates + ",20 " + query,
                                         page)
                if country:
                    results = api.search("country:" + country + " " + query,
                                         page)
            except Exception as e:
                print(e)

        if fail == 1:
            try:
                time.sleep(10)
                if coordinates:
                    results = api.search("geo:" + coordinates + ",20 " + query,
                                         page)
                if country:
                    results = api.search("country:" + country + " " + query,
                                         page)
            except Exception as e:
                results = False
                print(e)

        try:
            total = results['total']

            if total == 0:
                print("no results")
                break
        except Exception as e:
            print(e)
            break

        pages = math.ceil(total / 100) + 1
        print(pages)
        for counter, result in enumerate(results['matches']):
            lat = str(result['location']['latitude'])
            lon = str(result['location']['longitude'])
            city = ""
            indicator = []
            # print(counter)
            # time.sleep(20)

            try:
                product = result['product']
            except:
                product = ""

            if 'vulns' in result:
                vulns = [*result['vulns']]
            else:
                vulns = ""

            if result['location']['city'] != None:
                city = result['location']['city']

            hostnames = ""
            try:
                if 'hostnames' in result:
                    hostnames = result['hostnames'][0]
            except:
                pass

            try:
                if 'SAILOR' in result['http']['title']:
                    html = result['http']['html']
                    soup = BeautifulSoup(html)
                    for gps in soup.find_all("span", {"id": "gnss_position"}):
                        coordinates = gps.contents[0]
                        space = coordinates.split(' ')
                        if "W" in space:
                            lon = "-" + space[2][:-1]
                        else:
                            lon = space[2][:-1]
                        lat = space[0][:-1]
            except Exception as e:
                pass

            if 'opts' in result:
                try:
                    screenshot = result['opts']['screenshot']['data']

                    with open(
                            "app_kamerka/static/images/screens/" +
                            result['ip_str'] + ".jpg", "wb") as fh:
                        fh.write(base64.b64decode(screenshot))
                        fh.close()
                        for i in result['opts']['screenshot']['labels']:
                            indicator.append(i)
                except Exception as e:
                    pass

            if query == "Niagara Web Server":
                try:
                    soup = BeautifulSoup(result['http']['html'],
                                         features="html.parser")
                    nws = soup.find("div", {"class": "top"})
                    indicator.append(nws.contents[0])
                except:
                    pass

            # get indicator from niagara fox
            if result['port'] == 1911 or result['port'] == 4911:
                try:
                    fox_data_splitted = result['data'].split("\n")
                    for i in fox_data_splitted:
                        if "station.name" in i:
                            splitted = i.split(":")
                            indicator.append(splitted[1])
                except:
                    pass

            # get indicator from tank
            if result['port'] == 10001:
                try:
                    tank_info = result['data'].split("\r\n\r\n")
                    indicator.append(tank_info[1])
                except:
                    pass

            if result['port'] == 2000:
                try:
                    ta_data = result['data'].split("\\n")
                    indicator.append(ta_data[1][:-3])
                except Exception as e:
                    pass

            if result['port'] == 502:
                try:
                    sch_el = result['data'].split('\n')
                    if sch_el[4].startswith("-- Project"):
                        indicator.append(sch_el[4].split(": ")[1])
                except:
                    pass

            if "GPGGA" in result['data']:
                try:
                    splitted_data = result['data'].split('\n')
                    for i in splitted_data:
                        if "GPGGA" in i:
                            msg = pynmea2.parse(i)
                            lat = msg.latitude
                            lon = msg.longitude
                            break
                except Exception as e:
                    print(e)

            if result['port'] == 102:
                try:
                    s7_data = result['data'].split("\n")
                    for i in s7_data:
                        if i.startswith("Plant"):
                            indicator.append(i.split(":")[1])
                        if i.startswith("PLC"):
                            indicator.append(i.split(":")[1])
                        if i.startswith("Module name"):
                            indicator.append(i.split(":")[1])
                except:
                    pass
            # get indicator from bacnet
            if result['port'] == 47808:
                try:
                    bacnet_data_splitted = result['data'].split("\n")
                    for i in bacnet_data_splitted:
                        if "Description" in i:
                            splitted1 = i.split(":")
                            indicator.append(splitted1[1])
                        if "Object Name" in i:
                            splitted2 = i.split(":")
                            indicator.append(splitted2[1])

                        if "Location" in i:
                            splitted3 = i.split(":")
                            indicator.append(splitted3[1])
                except:
                    pass

            device = Device(search=search,
                            ip=result['ip_str'],
                            product=product,
                            org=result['org'],
                            data=result['data'],
                            port=str(result['port']),
                            type=search_type,
                            city=city,
                            lat=lat,
                            lon=lon,
                            country_code=result['location']['country_code'],
                            query=search_type,
                            category=category,
                            vulns=vulns,
                            indicator=indicator,
                            hostnames=hostnames,
                            screenshot=screenshot)
            device.save()

        page = page + 1
        if not all_results:
            results = False
示例#16
0
from shodan import Shodan
import re

api = Shodan('XXXXXXXXXXXXXXXXXXX')



def final(query,level):
        if level=='1':
            return (api.search(query,page=2,limit=10, offset=None, facets=None, minify=True))
        elif level=='2':
            return (api.search(query,page=None,limit=None, offset=None, facets=None, minify=True))
        elif level=='3':
            return (api.search(query,page=15,limit=None, offset=8, facets=None, minify=True))
        else:
            return("ERROR!!!!")        

def sh(query,resp):
    level='1'
    if re.findall("--level\s[0-3]",query):
        level=str(re.findall("--level\s[0-3]",query)[0].replace("--level ",""))
        query=query.replace("--level {}".format(level),"")
        #print (query)
        out=final(query,level)
        for i in out['matches']:
            resp.message("{}\n".format(("IP: {}\nOS: {}\nISP: {}\nPostal Code: {}\nCity Name: {}\nCountry Name: {}".format(i['ip_str'],i['os'],i['isp'],i['location']['postal_code'],i['location']['city'],i['location']['country_name']))))
        return resp    
    else:
        if re.findall("--level\s[0-9]",query):
            level=str(re.findall("--level\s[0-9]",query)[0].replace("--level ",""))
            query=query.replace("--level {}".format(level),"")
from shodan import Shodan
import sys

domain = sys.argv[1]
hosts=[]
api = Shodan('YOUR_API_KEY')

results=api.search('hostname:.{}'.format(domain))
try:
	for res in results['matches']:
		hosts.append(''.join(res['hostnames']))
except KeyError:
	pass

with open('shodan_subdomains.txt', 'w') as f:
    for item in hosts:
        f.write("%s\n" % item)
#return hosts
示例#18
0
def Search(Query_List, Task_ID, Type, **kwargs):

    try:
        Data_to_Cache = []
        Directory = General.Make_Directory(Plugin_Name.lower())
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        Log_File = General.Logging(Directory, Plugin_Name.lower())
        handler = logging.FileHandler(os.path.join(Directory, Log_File), "w")
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter("%(levelname)s - %(message)s")
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        Shodan_API_Key = Load_Configuration()
        API_Session = Shodan(Shodan_API_Key)
        Cached_Data = General.Get_Cache(Directory, Plugin_Name)
        Query_List = General.Convert_to_List(Query_List)
        Limit = General.Get_Limit(kwargs)

        for Query in Query_List:

            try:

                if Type == "Search":
                    Local_Plugin_Name = Plugin_Name + "-Search"

                    try:
                        API_Response = API_Session.search(Query)

                    except Exception as e:
                        logging.error(
                            f"{General.Date()} - {__name__.strip('plugins.')} - {str(e)}."
                        )
                        break

                    JSON_Output_Response = json.dumps(API_Response,
                                                      indent=4,
                                                      sort_keys=True)
                    Main_File = General.Main_File_Create(
                        Directory, Local_Plugin_Name, JSON_Output_Response,
                        Query, The_File_Extensions["Main"])
                    Output_Connections = General.Connections(
                        Query, Local_Plugin_Name, Domain, "Domain Information",
                        Task_ID, Plugin_Name.lower())
                    Current_Step = 0

                    for Shodan_Item in API_Response["matches"]:
                        Shodan_Item_Module = Shodan_Item['_shodan']['module']
                        Shodan_Item_Module = Shodan_Item_Module.replace(
                            '-simple-new', '')

                        if Shodan_Item_Module.startswith("http"):
                            Shodan_Item_Host = ""
                            Shodan_Item_Port = 0

                            if 'http' in Shodan_Item:
                                Shodan_Item_Host = Shodan_Item['http']['host']
                                Shodan_Item_Response = Shodan_Item['http'][
                                    'html']

                            elif 'ip_str' in Shodan_Item and 'domains' in Shodan_Item and len(
                                    Shodan_Item['domains']) > 0:
                                Shodan_Item_Host = Shodan_Item['domains'][0]
                                Shodan_Item_Response = Shodan_Item['data']

                            elif 'ip_str' in Shodan_Item and 'domains' not in Shodan_Item:
                                Shodan_Item_Host = Shodan_Item['ip_str']
                                Shodan_Item_Response = Shodan_Item['data']

                            if Shodan_Item_Host:

                                if 'port' in Shodan_Item_Host:

                                    if int(Shodan_Item['port']) not in [
                                            80, 443
                                    ]:
                                        Shodan_Item_Port = Shodan_Item['port']

                                if Shodan_Item_Port != 0:
                                    Shodan_Item_URL = f"{Shodan_Item_Module}://{Shodan_Item_Host}:{str(Shodan_Item_Port)}"

                                else:
                                    Shodan_Item_URL = f"{Shodan_Item_Module}://{Shodan_Item_Host}"

                                Title = "Shodan | " + str(Shodan_Item_Host)

                                if Shodan_Item_URL not in Cached_Data and Shodan_Item_URL not in Data_to_Cache and Current_Step < int(
                                        Limit):
                                    Output_file = General.Create_Query_Results_Output_File(
                                        Directory, Query, Local_Plugin_Name,
                                        Shodan_Item_Response, Shodan_Item_Host,
                                        The_File_Extensions["Query"])

                                    if Output_file:
                                        Output_Connections.Output(
                                            [Main_File, Output_file],
                                            Shodan_Item_URL, Title,
                                            Plugin_Name.lower())
                                        Data_to_Cache.append(Shodan_Item_URL)

                                    else:
                                        logging.warning(
                                            f"{General.Date()} - {__name__.strip('plugins.')} - Failed to create output file. File may already exist."
                                        )

                                    Current_Step += 1

                elif Type == "Host":
                    Local_Plugin_Name = Plugin_Name + "-Host"

                    try:
                        API_Response = API_Session.host(Query)

                    except Exception as e:
                        logging.error(
                            f"{General.Date()} - {__name__.strip('plugins.')} - {str(e)}."
                        )
                        break

                    JSON_Output_Response = json.dumps(API_Response,
                                                      indent=4,
                                                      sort_keys=True)
                    Main_File = General.Main_File_Create(
                        Directory, Local_Plugin_Name, JSON_Output_Response,
                        Query, The_File_Extensions["Main"])
                    Output_Connections = General.Connections(
                        Query, Local_Plugin_Name, Domain, "Domain Information",
                        Task_ID, Plugin_Name.lower())
                    Shodan_URL = f"https://www.{Domain}/host/{Query}"
                    Title = "Shodan | " + Query

                    if Shodan_URL not in Cached_Data and Shodan_URL not in Data_to_Cache:
                        Shodan_Responses = General.Request_Handler(
                            Shodan_URL,
                            Application_JSON_CT=True,
                            Accept_XML=True,
                            Accept_Language_EN_US=True,
                            Filter=True,
                            Host=f"https://www.{Domain}")
                        Shodan_Response = Shodan_Responses["Filtered"]
                        Output_file = General.Create_Query_Results_Output_File(
                            Directory, Query, Plugin_Name, Shodan_Response,
                            Query, The_File_Extensions["Query"])

                        if Output_file:
                            Output_Connections.Output([Main_File, Output_file],
                                                      Shodan_URL, Title,
                                                      Plugin_Name.lower())
                            Data_to_Cache.append(Shodan_URL)

                        else:
                            logging.warning(
                                f"{General.Date()} - {__name__.strip('plugins.')} - Failed to create output file. File may already exist."
                            )

                    else:
                        logging.warning(
                            f"{General.Date()} - {__name__.strip('plugins.')} - No results found."
                        )

            except:
                logging.warning(
                    f"{General.Date()} - {__name__.strip('plugins.')} - Failed to complete task."
                )

        General.Write_Cache(Directory, Cached_Data, Data_to_Cache, Plugin_Name)

    except Exception as e:
        logging.warning(
            f"{General.Date()} - {__name__.strip('plugins.')} - {str(e)}")
示例#19
0
 def setup(self):
     from shodan import Shodan
     self.api = Shodan(self.plugin_config["api_key"])
示例#20
0
from shodan import Shodan

# Register in shodan.io to get your api key
shodan_key = ''

api = Shodan(shodan_key)

try:
    query = api.search('struts')
    print(f'Found {query["total"]}')
    for host in query['matches']:
        print('-----------------------------')
        print(f'IP: {host["ip_str"]}')
        print(f'Port: {host["port"]}')
        print(f'ORG: {host["org"]}')
        try:
            print(f'ASN {host["asn"]}')
        except:
            pass
        for l in host['location']:
            print(f'{l}: {str(host["location"][l])}')
        # more details...
        # print(host['data'])
        print('-----------------------------')
except Exception as e:
    print(e)
示例#21
0
 def __init__(self):
     self.key = Core.shodan_key()
     if self.key is None:
         raise MissingKey(True)
     self.api = Shodan(self.key)
     self.hostdatarow = []
示例#22
0
    def run(self, args, lookup, report_directory, api_key_directory):
        """main function"""
        self.shodan_query_result = []
        self.shodan_api_key = None
        self.api_key_value = None
        #first if  https://shodan.readthedocs.io/en/latest/tutorial.html#connect-to-the-api
        #else https://shodan.readthedocs.io/en/latest/tutorial.html#looking-up-a-host

        #check for a stored api key, if missing ask for it and if it should be saved
        if not os.path.exists(api_key_directory + 'shodan.key'):
            print('[!] You are missing {}shodan.key'.format(api_key_directory))
            self.api_key_value = getpass.getpass(
                '[i] Please provide an API Key: ')
            response = raw_input(
                '[i] Would you like to save this key to a plaintext file? (y/n): '
            )

            if 'y' in response.lower():
                with open(api_key_directory + 'shodan.key',
                          'w') as api_key_file:
                    api_key_file.writelines(self.api_key_value)
            else:
                pass

        with open(api_key_directory + 'shodan.key') as f:
            self.api_key_value = f.readlines()[0]

        #invoke api with api key provided
        shodanApi = Shodan(self.api_key_value)

        #roll through the lookup list from -i or -d
        for i, l in enumerate(lookup):
            #open output file
            shodan_text_output = open(
                report_directory + l + '/' + l + '_shodan.txt', 'w')
            #user notification that something is happening
            print('[+] Querying Shodan via API search for {}'.format(l))
            try:
                #set results to api search of current lookup value
                #https://shodan.readthedocs.io/en/latest/examples/basic-search.html
                result = shodanApi.search(query="hostname:" + l)
                print('[+] Shodan found: {} hosts'.format(str(
                    result['total'])))
                #for each result
                for service in result['matches']:
                    if args.verbose is True:
                        print(str(service['ip_str'].encode('utf-8')+\
                            ' ISP: '+service['isp'].encode('utf-8')+\
                            ' Last seen: '+service['timestamp'].encode('utf-8')))
                    if args.verbose is True:
                        #print and encode if there are non-us chars
                        print(service['data'].encode('utf-8'))
                    #append to shodanResult list
                    self.shodan_query_result.append(str(\
                        service['ip_str'].encode('utf-8')+\
                        '\nISP:'+service['isp'].encode('utf-8')+\
                        '\nLast seen:'+service['timestamp'].encode('utf-8'))+\
                        '\n'+service['data'].encode('utf-8'))

            #catch exceptions
            except Exception as e:
                #print excepted error
                print('[-] Shodan Error: {} '.format(e))
                print(
                    '[!] You may need to specify an API key with -s <api key>')
                return

        #write contents of shodanResult list. this needs formatted
        shodan_text_output.writelines('[+] Shodan found: {} hosts\n\n'.format(
            str(result['total'])))
        shodan_text_output.writelines(self.shodan_query_result)

        return self.shodan_query_result
示例#23
0
def shodan_host_ip(target):
    ms = 'def shodan_host_ip: ' + target
    fn_core.edit_log(fn_default.log_full_path, ms, lvl='info')
    config = fn_core.import_config()
    apikey = config['shodan']['api-key']
    api = Shodan(apikey)
    # print(api.host(target))
    response = api.host(target)
    person_string = json.dumps(response)
    result = json.loads(person_string)
    print(fn_core.highlight("black", "█▓▒░ Shodan ░▒▓█"))
    print('\n')
    print(fn_core.highlight("black", "Host IP "))

    if str(result['area_code']) != 'null':
        print('area_code: ' + str(result['area_code']))
    if str(result['asn']) != 'null':
        print('asn: ' + str(result['asn']))
    if str(result['city']) != 'null':
        print('city: ' + str(result['city']))
    if str(result['country_code']) != 'null':
        print('country_code: ' + str(result['country_code']))
    if str(result['country_code3']) != 'null':
        print('country_code3: ' + str(result['country_code3']))
    if str(result['country_name']) != 'null':
        print('country_name: ' + str(result['country_name']))
    # if result['data']:
    #     print('data: ')
    # if result['data']:
    #     print('data: ')
    # for i in result['data']:
    # i = json.dumps(result)
    # i = json.loads(i)
    # print('\t' + 'positives: ' + str(i['positives']))
    # print('vulns: ')
    # if i['vulns']:
    #     for k in i['vulns']:
    #         k = json.dumps(k)
    #         k = json.loads(k)
    #         print('\t' + k)
    # print('\t' + 'asn: ' + str(i['asn']))
    # print('\t' + 'domains: ' + str(i['domains']))
    # print('\t' + 'hostnames: ' + str(i['hostnames']))
    # print('\t' + 'isp: ' + str(i['isp']))
    # print('\t' + 'org: ' + str(i['org']))
    # print('\t' + 'port: ' + str(i['port']))
    # print('vulns: ' + result['vulns'])
    # for i in result['data']:
    if 'vulns' in result:
        print('vulns: ')
        if result['vulns']:
            for k in result['vulns']:
                k = json.dumps(k)
                k = json.loads(k)
                print('\t' + k)
    if str(result['domains']) != 'null':
        print('domains: ' + str(result['domains']))
    if str(result['hostnames']) != 'null':
        print('hostnames: ' + str(result['hostnames']))
    if str(result['ip_str']) != 'null':
        print('ip_str: ' + str(result['ip_str']))

    if str(result['isp']) != 'null':
        print('isp: ' + str(result['isp']))
    if str(result['last_update']) != 'null':
        print('last_update: ' + str(result['last_update']))
    if str(result['latitude']) != 'null':
        print('latitude: ' + str(result['latitude']))
    if str(result['longitude']) != 'null':
        print('longitude: ' + str(result['longitude']))
    if str(result['org']) != 'null':
        print('org: ' + str(result['org']))
    if str(result['os']) != 'null':
        print('os: ' + str(result['os']))
    if str(result['ports']) != 'null':
        print('ports: ' + str(result['ports']))
    if str(result['postal_code']) != 'null':
        print('postal_code: ' + str(result['postal_code']))
    if str(result['region_code']) != 'null':
        print('region_code: ' + str(result['region_code']))
    if str(result['tags']) != 'null':
        print('tags: ' + str(result['tags']))
        # keys = k.keys()
        # values = k.values()
        # print(keys)
        # print(json.dumps(i['vulns'],indent=4,sort_keys=True))
        # print(fn_core.highlight("red", '\t' + 'positives: ' + str(i['positives'])))
        # print('\t' + 'scan_date: ' + str(i['scan_date']))
        # print('\t' + 'total: ' + str(i['total']))
        # print('\t' + 'url: ' + str(i['url']))
    # print('country-code: ' + str(result['country-code']))
    # print('country-code3: ' + str(result['country-code3']))
    # print('currency-code: ' + str(result['currency-code']))
    # print('ip: ' + str(result['ip']))
    # if result['host-domain']:
    #     print('host-domain: ' + str(result['host-domain']))
    # if result['hostname']:
    #     print('hostname: ' + str(result['hostname']))
    # if result['is-bogon']:
    #     print(fn_core.highlight("red", 'is-bogon: ' + str(result['is-bogon'])))
    #
    #
    f = json.dumps(result, indent=4, sort_keys=True)
    return f
示例#24
0
文件: favUp.py 项目: w4fz5uck5/fav-up
import sys
import requests
import base64

import mmh3
from ipwhois import IPWhois
from bs4 import BeautifulSoup
from shodan import Shodan

shodan = Shodan(open("SHODAN_API.txt", "r").readline())


def faviconHash(data, source):
    if source == "web":
        b64data = base64.encodebytes(data).decode()
    else:
        b64data = base64.encodebytes(data)
    return mmh3.hash(b64data)


def searchFaviconHTML(link):
    data = requests.get(link, stream=True)
    soup = BeautifulSoup(data.content, 'html.parser')
    iconLink = soup.find('link', rel='icon').get("href")
    if not iconLink.startswith("http"):
        iconLink = link + "/" + iconLink
    return requests.get(iconLink)


def shodanSearch(favhash):
    results = shodan.search(f"http.favicon.hash:{favhash}")
示例#25
0
    import platform
    import re
    import time
    #from pexpect import pxssh # Not supported on windows
    import termcolor
except ModuleNotFoundError:
    exit("Please install requirements.txt (pip install -r requirements.txt")

# Check to see if the Shodan Module exists.
# We don't wanna enforce it but only allow if installed
# will need to add to requirements.txt beforehand to make sure
try:
    from shodan import Shodan

    API_KEY = 'INSERT_API_KEY_HERE'
    SHODAN_API = Shodan(API_KEY)
except ModuleNotFoundError:
    pass

from requests.auth import HTTPBasicAuth
from subprocess import Popen, PIPE
from threading import *

# [IP's for Testing on Home Network]
# 10.10.10.254 : Default Address for CloudHub
# 192.168.0.34 : Home Machine for testing purposes
# 192.168.0.1  : Common Home Router Address
# 192.168.0.254: BTHomeHub Default Address
aliveHosts = []
discoveredPorts = []
示例#26
0
    def run(self):
        if self.keyFile:
            self.shodan = Shodan(open(self.keyFile, "r").readline().strip())
        elif self.key:
            self.shodan = Shodan(self.key)
        elif self.shodanCLI:
            self.shodan = Shodan(get_api_key())
        else:
            print('[x] Wrong input API key type.')
            exit(1)

        if self.faviconFile or self.fileList:
            self.fileList.extend(self.faviconFile)
            for fav in self.fileList:
                self._iterator.set_description(
                    f"[+] iterating over favicon files | processing {fav}")
                self._iterator.update(1)
                data = open(fav, 'rb').read()
                _fH = self.faviconHash(data)
                self.faviconsList.append({
                    'favhash': _fH,
                    'file': fav,
                    '_origin': fav
                })
        if self.faviconURL or self.urlList:
            self.urlList.extend(self.faviconURL)
            for fav in self.urlList:
                self._iterator.set_description(
                    f"[+] iterating over favicon URLs | processing {fav}")
                self._iterator.update(1)
                headers = {
                    'User-Agent': self.get_user_agent(),
                }
                data = requests.get(fav, stream=True, headers=headers)
                _dcL = self.deepConnectionLens(data)
                data = data.content
                _fH = self.faviconHash(data)
                self.faviconsList.append({
                    'favhash': _fH,
                    'url': self.faviconURL,
                    'domain': fav,
                    'maskIP': _dcL['mIP'],
                    'maskISP': _dcL['mISP'],
                    '_origin': fav
                })
        if self.web or self.webList:
            self.webList.extend(self.web)
            for w in self.webList:
                self._iterator.set_description(
                    f"[+] iterating over domains | processing {w}")
                self._iterator.update(1)
                try:
                    headers = {
                        'User-Agent': self.get_user_agent(),
                    }
                    data = requests.get(f"https://{w}",
                                        stream=True,
                                        headers=headers)
                    _dcL = self.deepConnectionLens(data)
                    data = self.searchFaviconHTML(f"https://{w}")
                    if not isinstance(data, str):
                        _fH = self.faviconHash(data.content, web_source=True)
                    else:
                        _fH = "not-found"
                except requests.exceptions.ConnectionError:
                    self._iterator.write(f"[x] Connection refused by {w}.")
                    if len(self.webList) == 1:
                        exit(1)
                self.faviconsList.append({
                    'favhash': _fH,
                    'domain': f"https://{w}",
                    'maskIP': _dcL['mIP'],
                    'maskISP': _dcL['mISP'],
                    '_origin': w
                })
        _alreadyScanned = {}

        _aF = set([f for i in self.faviconsList for f in i])
        _aF.remove('_origin')
        _aF.add('found_ips')

        _cObj = {}
        for f in _aF:
            _cObj.update({f: ''})

        if self.output:
            if self._output['type'].lower() == 'csv':
                self._output['file'].write(','.join(f for f in _aF) + '\n')

        self._iterator.reset(total=len(self.faviconsList))
        for _fObject in self.faviconsList:
            self._iterator.set_description(
                f"[+] lookup for {_fObject['favhash']}")
            self._iterator.update(1)
            try:
                _ = _alreadyScanned[_fObject['favhash']]
            except KeyError:
                found_ips = "not-found"
                if _fObject['favhash'] != "not-found":
                    found_ips = self.shodanSearch(_fObject['favhash'])
                _alreadyScanned.update({_fObject['favhash']: found_ips})
            found_ips = _alreadyScanned[_fObject['favhash']]
            _fObject.update({'found_ips': found_ips})

            if self.show:
                self._iterator.write("-" * 25)
                self._iterator.write(f"[{_fObject['_origin']}]")
                del _fObject['_origin']
                for _atr in _fObject:
                    self._iterator.write(f"--> {_atr:<10} :: {_fObject[_atr]}")

            if self.output:
                _tcObj = _cObj
                _tcObj.update(_fObject)
                _t = self._output['type']
                if _t.lower() == 'csv':
                    self._output['file'].write(','.join(
                        str(_tcObj[k]) for k in _tcObj) + '\n')
                elif _t.lower() == 'json':
                    self._output['file'].write(json.dumps(_tcObj) + '\n')
                else:
                    self._iterator.write(
                        "[x] Output format not supported, closing.")
                    exit(1)
示例#27
0
import sys
from shodan import Shodan
from config import shodan_key

try:
    sho = Shodan(shodan_key)
    # query = ' '.join("120.50.13.165")
    result = sho.host("123.245.10.187", minify=True)
    print(result)
    # sample result
    # result = {
    #     'region_code': '81',
    #     'tags': [],
    #     'ip': 2016546213,
    #     'area_code': None,
    #     'latitude': 23.729000000000013,
    #     'hostnames': ['NEW-ASSIGNED-FROM-APNIC-20-03-2008.telnet.net.bd'],
    #     'postal_code': '1000',
    #     'dma_code': None,
    #     'country_code': 'BD',
    #     'org': 'Telnet Communication Limited',
    #     'data': [],
    #     'asn': 'AS38712',
    #     'city': 'Dhaka',
    #     'isp': 'Telnet Communication Limited',
    #     'longitude': 90.41120000000001,
    #     'last_update': '2019-01-16T16:39:57.393738',
    #     'country_code3': 'BGD',
    #     'country_name': 'Bangladesh',
    #     'ip_str': '120.50.13.165',
    #     'os': None,
示例#28
0
文件: bt.py 项目: HaiChecker/tttt
# coding=utf-8
from shodan import Shodan
import requests

api = Shodan('PSKINdQe1GyxGgecYz2191H2JoS9qvgD')

for i in range(1, 20):
    print('开始第:{}页'.format(i))
    results = api.search('port:"888"', i)
    if len(results['matches']) > 0:
        for result in results['matches']:
            try:
                url = "http://" + result['ip_str'] + ":888/pma"
                res = requests.get(url)
                if res.status_code == 200:
                    print('接口状态:{} 地址:{}'.format(200, url))
            except:
                pass
    else:
        print '结束'
        break
示例#29
0
 def __init__(self, api_key=DefaultValues.SHODAN_API_KEY):
     self.api = Shodan(api_key)
     self.results: list = []
     self.shodan_results_count: int = 0
     self.real_results_count: int = 0
from shodan import Shodan
import json

api = Shodan('key')  #Get key from shodan API

# Lookup an IP
verified_cve = {}
hosts = ['152.1.109.5', '152.1.220.152', '152.1.52.127', '152.7.99.62']

for host in hosts:
    ipinfo = api.host(host)
    print(host)
    print(ipinfo['vulns'])
    for data in ipinfo['data']:
        if 'vulns' in data:
            for cve, ele in data['vulns'].items():
                if ele['verified']:
                    verified_cve[cve] = ele['summary']
    #printing only summary of the CVE whose verified flag is set to True
    print(verified_cve)
    print("\n")