Python操作ZoomeyeAPI

最近用了用Zoomeye,发现是真好用,而且还免费开放了API,用Python封装了一个操作类,自己以后也用着方便。

代码

import requests
import json
import os

class ZoomeyeAPIAction(object):
    def __init__(self, username, password):
        self.__username = username
        self.__password = password
        self.__accessToken = ''

    def __login(self):
        data = {
            'username': self.__username,
            'password': self.__password,
        }
        jsonData = json.dumps(data, indent=4)
        try:
            r = requests.post('https://api.zoomeye.org/user/login', data=jsonData)
            result = json.loads(r.text)
            self.__accessToken = result['access_token']
        except Exception as e:
            print('[-] Username or password is wrong')
            os._exit(1)

    def __saveFile(self, filename, content):
        with open(filename, 'a') as f:
            f.write(content+'\n')
            f.close()

    def __readFile(self, filename):
        with open(filename, 'r') as f:
            return f.readlines()

    def __getAccessToken(self):
        if os.path.isfile('access_token.txt'):
            with open('access_token.txt', 'r') as f:
                self.__accessToken = f.read().strip()
                f.close()
        else:
            self.__login()
            self.__saveFile('access_token.txt', self.__accessToken)

    #flag开控制是主机搜索还是web应用搜索
    def __getQuery(self, flag, query, page='', facets=''):
        query = '?query=' + query
        page = '' if not page else ('&page='+str(page))
        facets = '' if not facets else ('&facets='+str(facets))
        queryUrl = 'https://api.zoomeye.org/'+flag+'/search'+query+page+facets
        return queryUrl

    #使用API会用页数限制,这里获取全部
    def search(self, flag, query, facets=''):
        self.__getAccessToken()
        page = 1

        while True:
            queryUrl = self.__getQuery(flag, query, page=page, facets=facets)
            r = requests.get(queryUrl, headers={'Authorization': 'JWT '+self.__accessToken})

            if 'error' in json.loads(r.text).keys():
                print('[-] Account was break, excceeding the max limitations. The page is', page)
                break

            filename = query.split(' ')[0]+'.json'
            if ':' in filename: filename = filename.replace(':', '-')
            if '"' in filename: filename = filename.replace('"', '')
            self.__saveFile('searchResult/'+filename, r.text)
            '''
            #可在此处控制页数
            if page >= 10:
                break
            '''
            page += 1

    #这里只写了一个获取查询结果ip的方法,其他可以自由扩展
    def getIp(self):
        jsonData = self.__readFile('searchResult/product-Docker.json')
        for line in jsonData:
            data = json.loads(line)
            for d in data['matches']:
                self.__saveFile('searchResult/ip.txt', d['ip'])

if __name__ == '__main__':
    zoomeye = ZoomeyeAPIAction('your_username', 'your_password')
    zoomeye.search('host', 'product:"Docker Remote API" country:"US"', 'os')
    zoomeye.getIp()
标签: none