← webhosting 6 min read
#webhosting

Here are individual articles for each step, explaining the purpose and functionality of the script:


Article 1: Introduction to Abuse IP Database and API Integration

In cybersecurity, monitoring and handling suspicious or malicious IP addresses is critical for maintaining network safety. Abuse IP DB is a platform that collects and reports data about potentially harmful IP addresses. Their API allows developers to automate IP address checks to identify if an IP is associated with suspicious activity.

In this guide, we will walk through a Python script that queries the Abuse IP DB API to check the reputation of a given IP address. This script uses the curl command (wrapped in Python) to send the request and fetch the response.


Article 2: Step 1 - Storing Sensitive Data: Using credentials.py for API Keys

Why use a credentials.py file?

Storing sensitive information like API keys directly in your main script is not a secure practice. By keeping the API key in a separate file, you can manage and secure the key more easily, especially if you share your main script publicly or work in a team.

Creating the credentials.py file:

Create a new Python file named credentials.py to store your API key securely. This file will contain a single variable, apikey, holding your key as a string:

# credentials.py
apikey = "YOUR_API_KEY_HERE"

The Result:

Now, we have a secure and easy-to-maintain place to store our API key, which we can import into our main script in the next step.


Article 3: Step 2 - Writing the ipCheck Function in Python

Now that we have stored our API key, let's write the Python script that will use it to query the Abuse IP DB API and return information about any IP address you pass to the function.

The main function we'll be working on is called ipCheck. This function takes an IP address as input, constructs a curl command to call the Abuse IP DB API, and returns the result in JSON format.

Code Explanation:

import credentials
import subprocess

def ipCheck(ip):
    # Get API key from credentials
    apikey = credentials.apikey

    # Construct curl command for hitting the API endpoint
    command = [
        'curl',
        '-sG',  # Use -sG to keep the request silent and in GET mode
        'https://api.abuseipdb.com/api/v2/check',
        '--data-urlencode', f'ipAddress={ip}',
        '-d', 'maxAgeInDays=90',  # Specify the max age of the IP report
        '-d', 'verbose',  # Get verbose information
        '-H', f'Key: {apikey}',  # API key header
        '-H', 'Accept: application/json'  # Ensure JSON response
    ]

    # Execute the curl command
    results = subprocess.run(command, capture_output=True, text=True)

    # Return the output (in JSON format)
    return results.stdout

The Result:

Once the function is executed, it will return a JSON response detailing whether the IP address has been involved in any suspicious activities and additional details about the report.


Article 4: Step 3 - Using subprocess.run() to Execute Curl Commands in Python

Why use subprocess.run()?

In Python, when you want to execute shell commands (like curl), you can use the subprocess module. In our case, we need to call the Abuse IP DB API using curl because it allows for sending complex requests, including headers and parameters, via the command line. By wrapping this command in Python, we can automate these requests.

Breakdown of the subprocess.run() function:

results = subprocess.run(command, capture_output=True, text=True)

The results.stdout will contain the JSON output from the API, which we return from the ipCheck function.

The Result:

With subprocess.run(), you can successfully execute a curl command from within Python and capture the API's response.


Article 5: Step 4 - Running the Script and Handling the Output

How to Run the Script:

To test the script, ensure you have your API key saved in credentials.py and run the following script:

import credentials
import subprocess

def ipCheck(ip):
    apikey = credentials.apikey
    command = [
        'curl', '-sG', 'https://api.abuseipdb.com/api/v2/check',
        '--data-urlencode', f'ipAddress={ip}',
        '-d', 'maxAgeInDays=90', '-d', 'verbose',
        '-H', f'Key: {apikey}', '-H', 'Accept: application/json'
    ]
    results = subprocess.run(command, capture_output=True, text=True)
    return results.stdout

# Example usage:
ip = "8.8.8.8"  # Google's public DNS IP for testing
print(ipCheck(ip))
  1. Import the credentials module: This ensures that the API key is securely pulled from credentials.py.
  2. Call the ipCheck function: You can pass any IP address to this function to get its report from Abuse IP DB.
  3. Print the results: The script will output the API response in JSON format.

Expected Output:

The output will be a JSON response that includes details like:

For example:

{
  "data": {
    "ipAddress": "8.8.8.8",
    "isPublic": true,
    "ipVersion": 4,
    "isWhitelisted": false,
    "abuseConfidenceScore": 0,
    "countryCode": "US",
    "usageType": "Data Center/Web Hosting/Transit",
    "domain": "google.com",
    "hostnames": [
      "dns.google"
    ],
    "totalReports": 0,
    "lastReportedAt": null
  }
}

The Result:

You now have a fully functional Python script that can query the Abuse IP DB API and return reputation data on any IP address.


Article 6: Conclusion and Final Thoughts

By following the steps outlined in this guide, you now have a Python script that automates the process of querying the Abuse IP DB API. Here's a summary of the key points:

This script can be integrated into a broader security monitoring system or used for checking specific IP addresses as needed.