当前位置: 首页>>代码示例>>Python>>正文


Python shodan.Shodan方法代码示例

本文整理汇总了Python中shodan.Shodan方法的典型用法代码示例。如果您正苦于以下问题:Python shodan.Shodan方法的具体用法?Python shodan.Shodan怎么用?Python shodan.Shodan使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在shodan的用法示例。


在下文中一共展示了shodan.Shodan方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _init_shodan

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def _init_shodan(self, shodan_api):
        parameters = {"shodan_api": shodan_api}
        n = self._database.execute("SELECT (SELECT count() from tbl_config) as count").fetchall()[0][0] 
        if isinstance(shodan_api, str):
            if n == 0:
                _ = self._database.execute("INSERT INTO tbl_config (shodan_api) VALUES (:shodan_api)", parameters)
            else:
                _ = self._database.execute("UPDATE tbl_config SET shodan_api=:shodan_api", parameters)

            self._database.commit()

            return shodan.Shodan(shodan_api)

        else:
            if n == 0:
                warn("No Shodan API key found (register a free account at https://account.shodan.io/register)")
            else:
                shodan_api = self._database.execute("SELECT shodan_api FROM tbl_config").fetchall()[0][0]
                if shodan_api:
                    return shodan.Shodan(shodan_api) 
开发者ID:malwaredllc,项目名称:bamf,代码行数:22,代码来源:bamf.py

示例2: gather_host_shodan

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def gather_host_shodan():
    api_shodan_key = open(path + "/api.txt","r").read()
    if api_shodan_key == "":
        print('no shodan api found, please insert a valid one')
        api_shodan_key_to_file = raw_input('\ntype here:')
        with open(path + "/api.txt", "wb") as api:
            api.write(api_shodan_key_to_file)
        api = shodan.Shodan(api_shodan_key)
    else:
        api = shodan.Shodan(api_shodan_key)
        try:
            query = raw_input("["+"*"+"]"+ " enter a valid shodan query:")
            response = api.search(query)
            with open(path +'/host.txt',"wb") as host:
                for service in response['matches']:
                    host.write(service['ip_str']+ ":" + str(service['port']))#host.write(service['port']
                    host.write("\n")
        except KeyboardInterrupt:
            print ("\n[---]exiting now[---]") 
开发者ID:M0tHs3C,项目名称:Hikxploit,代码行数:21,代码来源:hikxploit_win.py

示例3: gather_host_shodan

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def gather_host_shodan():
    api_shodan_key = open(path + "/api.txt","r").read()
    if api_shodan_key == "":
        print(t.red('no shodan api found, please insert a valid one'))
        api_shodan_key_to_file = raw_input('\ntype here:')
        with open(path + "/api.txt", "wb") as api:
            api.write(api_shodan_key_to_file)
        api = shodan.Shodan(api_shodan_key)
    else:
        api = shodan.Shodan(api_shodan_key)
        try:
            query = raw_input("["+t.blue("*")+"]"+ " enter a valid shodan query:")
            response = api.search(query)
            with open(path +'/host.txt',"wb") as host:
                for service in response['matches']:
                    host.write(service['ip_str']+ ":" + str(service['port']))#host.write(service['port']
                    host.write("\n")
        except KeyboardInterrupt:
            print t.red("\n[---]exiting now[---]") 
开发者ID:M0tHs3C,项目名称:Hikxploit,代码行数:21,代码来源:hikxploit.py

示例4: initialize

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def initialize(self, base_dir):
        if self.skey:
            logger.info('Initializing the shodan api.')
            result = os.system('shodan init {skey}'.format(skey=self.skey))
            if result:
                logger.warning('Initializ failed, please check your key.')
                return False
            self.conf.set("shodan", "shodan_key", self.skey)
            self.conf.write(open(base_dir + "/key.ini", "w"))
            self.api = Shodan(get_api_key())
        else:
            from click.exceptions import ClickException
            try:
                key = None if get_api_key() == '' else get_api_key()
                if key:
                    self.api = Shodan(key)
                else:
                    return False
            except ClickException as e:
                logger.warning('The shodan api is empty so you can not use shodan api.')
                return False
        return True 
开发者ID:FeeiCN,项目名称:ESD,代码行数:24,代码来源:__init__.py

示例5: _handle_shodan_from_api

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def _handle_shodan_from_api(self):
        api = shodan.Shodan(SHODAN_API_KEY)
        table = PrettyTable(field_names=[
            'IP', 'Port', 'ASN', 'Version', 'Organization', 'Hostnames'
        ])

        table.align['ASN'] = "l"
        table.align['Organization'] = "l"
        table.align['Hostnames'] = "l"

        self.print_info('Fetching Shodan data...')

        for item in api.search_cursor('MQTT Connection Code: 0'):
            table.add_row([
                item.get('ip_str', '-'),
                item.get('port', 0),
                item.get('asn', '-'),
                item.get('version', '-'),
                item.get('org', '-'),
                ', '.join(item.get('hostnames', [])) or '-',
            ])

        self.ppaged(msg=str(table))
        export_table(table) 
开发者ID:akamai-threat-research,项目名称:mqtt-pwn,代码行数:26,代码来源:shodan.py

示例6: shodan_q

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def shodan_q():
	global logging
	
	print "\n[" + t.green("+") + "]Please provide a search query. I.e 'cisco' will return all known vulns for that item" 
	
	query = raw_input("\n<" + t.cyan("SHODAN") + ">$ " )
	
	try:
		api = shodan.Shodan(SHODAN_API_KEY)
		results = api.exploits.search(query, 5, 'author, platform, port, type')
	except Exception as e:
		print "\n[" + t.red("!") + "]Critical. An error was raised with the following error message"
		print e
	
	format = json.dumps(results, indent = 2)	
	print format
	
	if logging == True:
		with open('shodan_cve.log', 'ab') as outfile:
			outfile.write(format)
			outfile.close()
			
		print "\n[" + t.green("+") + "]Results have been saved to 'shodan_cve.log' in the current directory." 
开发者ID:NullArray,项目名称:PyParser-CVE,代码行数:25,代码来源:cveparser.py

示例7: port_scan

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def port_scan(hostx, key, counter):
    api = shodan.Shodan(key)
    numports = 0

    for IP in hostx.resolved_ips:
        try:
            query = api.host(IP.address)
            IP.ports = query['ports']
            IP.vulns = query['vulns']
            IP.server = query['server']
            # print (query['vulnerabilities'])
            counter.ports = counter.ports + len(hostx.ports)
            counter.vulns = counter.vulns + len(hostx.vulns)
        except:
            time.sleep(1)
            continue 
开发者ID:superhedgy,项目名称:AttackSurfaceMapper,代码行数:18,代码来源:shodan.py

示例8: search

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def search(
        self, query: str, max_records=DefaultValues.SHODAN_DEFAULT_RESULTS_QUANTITY
    ) -> None:
        """
        Search for defined query in Shodan database
        :param query: query to search for
        :param max_records: quantity of max records to search
        :return: None
        """
        try:
            results_generator = self.api.search_cursor(query, minify=True)
            self.results = list(islice(results_generator, max_records))
            self._remove_unused_fields_in_vulns()
            self.shodan_results_count = self.api.count(query).get("total")
        except (APIError, APITimeout) as api_error:
            print(f"Shodan API error: {api_error}")
        self.real_results_count = len(list(self.results)) 
开发者ID:sdnewhop,项目名称:grinder,代码行数:19,代码来源:shodanconnector.py

示例9: main

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def main():

    API_KEY = input("Enter your shodan api key: ")
    # If you don't want enter your shodan key every time you can define API_KEY as a string like API_KEY = "YOUR_SHODAN_KEY"
    api = shodan.Shodan(API_KEY)
    try:
        prod = input("Enter product name: ")
        res = api.search(prod)

        print("Results found {}".format(res['total']))
        for r in res['matches']:
            print("IP: {}".format(res['ip_str']))
            print(res['data'])
            print("")

    except shodan.APIError as e:
        print("Error: {}".format(e))

    except KeyboardInterrupt:
        print("Exiting...")
        exit(0) 
开发者ID:Naategh,项目名称:PyCk,代码行数:23,代码来源:shodan-prod.py

示例10: prep_host

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def prep_host(host_data, hostname):
    os = host_data['os']
    hostname = hostname
    host_port = f"{host_data['ip_str']}:{host_data['port']}"
    source = 'Shodan'
    screen_name = host_port
    profile_name = host_port
    profile_url = f"http://{host_port}"
    media_url = f"https://www.shodan.io/host/{host_data['ip_str']}"
    thumb_url = 'https://gravatar.com/avatar/ffc4048d63729d4932fd3cc45139174f?s=300'
    message = (
        f"Hostname: {hostname} | City: {host_data['location']['city']} | State: {host_data['location']['region_code']} "
        f"| Country: {host_data['location']['country_name']} | OS: {os}")
    latitude = host_data['location']['latitude']
    longitude = host_data['location']['longitude']
    time = datetime.strptime(host_data['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')
    return source, screen_name, profile_name, profile_url, media_url, thumb_url, message, latitude, longitude, time 
开发者ID:lanmaster53,项目名称:recon-ng-marketplace,代码行数:19,代码来源:shodan.py

示例11: shodan_ip_search

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def shodan_ip_search(shodan_search_object, shodan_search_ip):
    port_target = []
    result = ""
    try:
        print "\nSearching Shodan for info about " + shodan_search_ip + "...\n"
        # Search Shodan
        result = shodan_search_object.host(shodan_search_ip)
        try:
            for i in result['data']:
               print 'Port: %s' % i['port']
               port_target.append(i['port'])
        except Exception as e:
            print e
    except Exception as e:
        print e
    return port_target 
开发者ID:n4xh4ck5,项目名称:N4xD0rk,代码行数:18,代码来源:sh4d0m.py

示例12: grab

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def grab(web):

    api = shodan.Shodan(SHODAN_API_KEY)
    print(GR+' [*] Resolving hostnames...')
    time.sleep(0.7)
    try:
        print(C+' [!] Parsing information...')
        hostIP = socket.gethostbyname(web)

        print(C+' [!] Setting query parameters...')
        host = api.host(hostIP)

        for item in host['data']:
            print(GR+'\n [+] Port : '+C+ str(item['port']))
            print(G+' [+] Banner :'+C+color.TR2+C+' \n')
            for q in str(item['data']).splitlines():
                if ':' in q:
                    print(O+'    '+q.split(':')[0]+' :'+C+color.TR3+C+G+q.split(':')[1].strip()+C+color.TR2+C)
                else:
                    print(C+'    '+q)
                    time.sleep(0.02)

    except KeyboardInterrupt:
        print(R+' [-] An error occured...\n') 
开发者ID:VainlyStrain,项目名称:Vaile,代码行数:26,代码来源:bannergrab.py

示例13: gather

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def gather(self, all_ips):

        for path, incoming_ip_obj in all_ips.iteritems():

            if incoming_ip_obj[0].shodan_info == "" and incoming_ip_obj[0].ip_address != "":

                if self.api_key is "":
                    print helpers.color("[*] Error: You didn't provide a Shodan API Key!", warning=True)
                    print helpers.color("[*] Please edit Shodan module and add in your API Key.", warning=True)
                else:
                    if incoming_ip_obj[0].shodan_info is '':
                        print "Querying Shodan for information about " + incoming_ip_obj[0].ip_address
                        try:
                            json_result = self.api_object.host(incoming_ip_obj[0].ip_address)
                            incoming_ip_obj[0].shodan_info = json_result
                        except shodan.exception.APIError:
                            incoming_ip_obj[0].shodan_info = "No available information within Shodan about " + incoming_ip_obj[0].ip_address
                        except simplejson.decoder.JSONDecodeError:
                            pass
        return 
开发者ID:FortyNorthSecurity,项目名称:Just-Metadata,代码行数:22,代码来源:get_shodn.py

示例14: iter_targets

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def iter_targets(targets, shodan_apikey):
        shodan_api = None
        if not shodan:
            LOGGER.warning(
                "[i] starting without shodan support. please pip install shodan to use shodan search strings.")
        else:
            if not shodan_apikey:
                LOGGER.warning("shodan apikey missing! shodan support disabled.")
            else:
                shodan_api = shodan.Shodan(shodan_apikey)

        for target in targets:
            if target.startswith("shodan://"):
                target = target.replace("shodan://", "")
                if shodan_api:
                    for t in shodan_api.search(target)['matches']:
                        yield t['ip_str'], t['port']
            else:
                host,port = target.strip().split(":")
                yield host,int(port) 
开发者ID:tintinweb,项目名称:pub,代码行数:22,代码来源:poc.py

示例15: __init__

# 需要导入模块: import shodan [as 别名]
# 或者: from shodan import Shodan [as 别名]
def __init__(self, dork, page, limit):
        key = Facade().sett.get('plugins', 'shodan_apikey')
        if not key:
            raise FuzzExceptMissingAPIKey("A Shodan api key is needed. Please check ~/.wfuzz/wfuzz.ini")

        self.api = shodan.Shodan(key)
        self._dork = dork
        self._page = MyCounter(page)
        self._page_limit = self._page() + limit if limit > 0 else -1

        self.results_queue = Queue(self.MAX_ENQUEUED_RES)
        self.page_queue = Queue()

        self._threads = []

        self._started = False
        self._cancel_job = False 
开发者ID:xmendez,项目名称:wfuzz,代码行数:19,代码来源:payloadtools.py


注:本文中的shodan.Shodan方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。