Skip to content
Related Articles

Related Articles

How to Build a SQL Injection Scanner in Python?
  • Last Updated : 03 Mar, 2021

In general terms, SQLi is the most prevalent and dangerous code insertion technique.  An SQLi attack is meant to send malicious SQL commands to the database server. The most common attack goal is bulk extraction of knowledge. Attackers can dump database tables with many thousands of customer records. Depending on the environment, SQL injection also can be exploited to switch or delete data, execute arbitrary OS commands, or launch denial-of-service (DoS) attacks.

Building SQL Injection Scanner in Python

Using the below approach we will extract the web forms first because SQL injection is carried through user input. Then, we will check whether a web page has SQL errors in it, this will be useful when checking for SQL injection attacks and finally, we will test it on HTML forms.

For this, we will require requests and BeautifulSoup package.


  • Import module
  • Now, initialize the session of HTTP and set the latest user agent for your browser
  • Now we shall extract the HTML web forms.
    • For this, first, we will write a function that upon giving a URL, will make a request to that page and will extract all the HTML form tags from it
    • Then return these tags as a list.
    • We can then use this list afterward.
  • Now we will check that whether the obtained page has any SQL vulnerabilities or not from its response output.
  • If it has any syntax error, the page is vulnerable. Although there are a lot of database errors we will search with limited database errors that is Oracle and SQL Server Errors, because these two are mostly used.
  • Now we will apply this search approach for all the forms in the HTML web page for the error
  • Our script is ready, and we will now test it.
    • We will pass the URL upon which we have to detect SQL injection.
    • So we will pass the URL argument through the command line.



import requests
from bs4 import BeautifulSoup
import sys
from urllib.parse import urljoin
s = requests.Session()
s.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
def get_forms(url):
    soup = BeautifulSoup(s.get(url).content, "html.parser")
    return soup.find_all("form")
def form_details(form):
    detailsOfForm = {}
    action = form.attrs.get("action").lower()
    method = form.attrs.get("method", "get").lower()
    inputs = []
    for input_tag in form.find_all("input"):
        input_type = input_tag.attrs.get("type", "text")
        input_name = input_tag.attrs.get("name")
        input_value = input_tag.attrs.get("value", "")
            {"type": input_type, "name": input_name, "value": input_value}
    detailsOfForm["action"] = action
    detailsOfForm["method"] = method
    detailsOfForm["inputs"] = inputs
    return detailsOfForms
def vulnerable(response):
    errors = {"quoted string not properly terminated",
              "unclosed quotation mark after the character string"
              "you have an error in your sql syntax;"}
    for error in errors:
        if error in response.content.decode().lower():
            return True
    return False
def sql_injection_scan(url):
    forms = get_forms(url)
    print(f"[+] Detected {len(forms)} forms on {url}.")
    for form in forms:
        details = form_details(form)
        for c in "\"'":
            data = {}
            for input_tag in details["inputs"]:
                if input_tag["type"] == "hidden" or input_tag["value"]:
                    data[input_tag["name"]] = input_tag["value"] + c
                elif input_tag["type"] != "submit":
                    data[input_tag["name"]] = f"test{c}"
            url = urljoin(url, form_details["action"])
            if details["method"] == "post":
                res =, data=data)
            elif details["method"] == "get":
                res = session.get(url, params=data)
            if vulnerable(res):
                print("SQL Injection attack vulnerability detected in link:", url)
                print("No SQL Injection vulnerability detected")
if __name__ == "__main__":


[+] Detected 0 forms on

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :