FOFA Python SDK

repository·master·Indexed 41 days ago

https://github.com/fofapro/fofa-py

A Python wrapper and CLI tool for the FOFA API used to integrate search engine data for Internet-connected devices. Features include the fofa.Client for executing queries via search(), search_next(), and search_stats(), as well as tools for retrieving host information and user account details. Requires Python 3.7+.

Tokens
3.2K
Snippets
15
Records
16
Agent score
50%

What's inside FOFA

  1. Install and use the FOFA Python SDK

    master

    The FOFA Python SDK is a wrapper for the FOFA API, allowing you to integrate search engine data for Internet-connected devices into your Python projects. It requires Python 3.7+.

    To use the SDK, you must initialize a fofa.Client with your FOFA API key and use the .search() method to execute queries.

    # -*- coding: utf-8 -*-
    import fofa
    
    if __name__ == "__main__":
        key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
        client = fofa.Client(key)               
        query_str = 'header="thinkphp" || header="think_template"'                           
        data = client.search(query_str, size=100, page=1, fields="ip,city") 
        for ip, city in data["results"]:
            print("%s,%s" % (ip, city))
  2. Initialize the FOFA Client

    master

    To interact with the FOFA API, you must instantiate the fofa.Client class. This client serves as the primary entry point for making authenticated requests to the FOFA service.

    import fofa
    
    # Example initialization
    client = fofa.Client(email='YOUR_EMAIL', key='YOUR_API_KEY')
  3. Use the fofa.Client.search method

    master

    The search method is used to query the FOFA API. Based on the usage example, it accepts the following parameters:

    • query_str: The FOFA query string (e.g., 'header="thinkphp"').
    • size: The number of results per page.
    • page: The page number to retrieve.
    • fields: A comma-separated string of fields to return (e.g., 'ip,city').

    Returns a dictionary containing the search results, typically under the key "results".

    data = client.search(query_str, size=100, page=1, fields="ip,city")
    # data["results"] contains the list of results
  4. Use the FOFA Python SDK

    master

    To integrate FOFA into your Python applications, use the fofa.Client class.

    1. Initialize: Create a client instance by passing your API key to fofa.Client(key).
    2. Search: Use client.search(query_str, size=..., page=..., fields=...) to retrieve data. The results are returned in a dictionary containing a "results" key.
    3. User Info: Use client.get_userinfo() to check your remaining FOFA points ("fofa_point").

    Note: The example below uses Python 2 style print syntax as provided in the source documentation.

    # -*- coding: utf-8 -*-
    import fofa
    
    if __name__ == "__main__":
        key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  # Your API Key
        client = fofa.Client(key)                # Initialize client
        query_str = 'header="thinkphp" || header="think_template"'
        
        for page in range(1, 51):               # Iterate through pages
            fpoint = client.get_userinfo()["fofa_point"] # Check remaining points
            if fpoint < 100:
                break                                   
            
            # Search for data
            data = client.search(query_str, size=100, page=page, fields="ip,city")
            for ip, city in data["results"]:
                print "%s,%s" % (ip, city)
  5. Use the FOFA CLI tool

    master

    The FOFA CLI tool provides a simple interface for querying FOFA data from the command line.

    List available commands

    Run fofa to see all supported commands.

    Search data

    Use the search subcommand to query data. You can specify fields with -f, result size with --size, and save output to a file with --save.

    • Basic search: fofa search <query> --size <number> -f <fields>
    • Count results: Use --count to get the total number of results for a query.
    • Aggregate information: Use --stats to query aggregated information.
    • Save to CSV/XLS: Use --save <filename> to export results.

    Host information

    Use the host subcommand to view detailed information (ASN, country, IP, ports, etc.) for a specific domain or IP.

    # Search and display results with specific fields
    fofa search domain=bing.com --size 1000 -f ip,port,domain,title,certs_match,certs_expired
    
    # Count total results
    fofa search domain=bing.com --count
    
    # Query aggregated information
    fofa search domain=bing.com -f port,domain,protocol,title --stats --size 10
    
    # Save results to a CSV file
    fofa search domain=bing.com -f ip,port,domain,link,title,certs_match,certs_expired --size 50000 --save bing.csv
    
    # View host information for a domain
    fofa host www.bing.com
  6. Use the FOFA Command-line Tool

    master

    The FOFA CLI is a tool for simple data queries. Use fofa to display all supported commands.

    search subcommand

    Used to search data from FOFA.

    • Search and display results: Use -f to specify fields and --size to set the result limit.
    • Count results: Use the --count flag to get the total number of matching results.
    • Query aggregation: Use --stats to get aggregation information for specific fields.
    • Save results: Use --save <filename> to export results to CSV or XLS format.

    host subcommand

    Used to view detailed host information for a specific domain or IP address.

    # Display all commands
    fofa
    
    # Search data with specific fields and size
    fofa search domain=bing.com --size 1000 -f ip,port,domain,title,certs_match,certs_expired
    
    # Count search results
    fofa search domain=bing.com --count
    
    # Query aggregation information
    fofa search domain=bing.com -f port,domain,protocol,title --stats --size 10
    
    # Save results to CSV
    fofa search domain=bing.com -f ip,port,domain,link,title,certs_match,certs_expired --size 50000 --save bing.csv
    
    # View host information
    fofa host www.bing.com
  7. Get current user information using get_userinfo()

    master

    The get_userinfo() method returns information about the current FOFA user, including VIP level, email, and balance (fcoin).

    user_info = client.get_userinfo()
    print(f"Username: {user_info['username']}, VIP: {user_info['isvip']}")
  8. Search host information using search_host()

    master

    The search_host() method retrieves detailed information for a specific IP address or domain.

    Parameters:

    • host (str): The IP address or domain to search.
    • detail (bool): If True, returns detailed information. Defaults to False.
    • opts (dict): Additional options.
    # Get detailed info for a specific host
    host_info = client.search_host('78.48.50.249', detail=True)
    print(host_info['country_name'])
  9. Query the next page of results using search_next()

    master

    The search_next() method allows for paginated traversal of search results using a pagination ID returned by previous queries.

    Parameters:

    • query_str (str): The search query string.
    • fields (str): Fields to include in the response. Defaults to 'host,ip,port'.
    • size (int): Number of results per page (Max: 10,000). Defaults to 100.
    • next (str): The pagination ID returned in the previous response. If omitted, the first page is returned.
    • full (bool): If True, searches all data. If False (default), searches within the past year.
    • opts (dict): Additional options.
    # Perform initial search
    first_page = client.search('app="webserver"', size=100)
    next_id = first_page['next'] # Assuming 'next' is in the response
    
    # Fetch the next page
    second_page = client.search_next('app="webserver"', next=next_id)