Saving bash script result in database.

Hi, I am currently doing a project and I just want to know how can I save the data from running bash script result. Like I want to run the bash script and I want to save the data in database then I want to show it on my html web page as a result. I am new to django.

Below is the function from views.py file

def subdomain(request):
    if request.GET.get('domain'):
        domain = request.GET.get('domain')
        process = Popen(["recon.sh {} | sort -u ".format(domain)], shell=True, stdout=PIPE, stderr=STDOUT)
        output_byte = process.stdout.read()
        result = str(output_byte)[2:-1].strip().split('\\n')
    
        return render(request,'scan/subdomain.html' , {'result':result})
    return render(request,'scan/subdomain.html')

This is my models.py:

class subscan(models.Model):
    subdomain = models.CharField(max_length=1000)
    ip_address = models.CharField(max_length=1000)

You’d want to use some model methods between result = str(... and return render

Also FYI when running scripts you need to be super careful for shell injection. Your current code allows e.g. domain to be set to ; rm -rf / ; echo and the script run will be recon.sh ; rm -rf / ; echo | sort -u - REMOVING everything on your disk !

Instead do not use shell=True, and sort the result in Python. Also use the new subprocess.run API to make things shorter and automatically convert the bytes to str. Putting it all together:

process = subprocess.run(["recon.sh", domain], capture_output=True, text=True)
if process.returncode != 0:
    # error handling - currently missing
output = process.stdout.read()
result = output[2:-1].strip().split('\\n')
result = list(set(result))  # unique
result.sort()
...

Hope that helps,

Adam

Hi, thank you for your suggestion. The shell script doesn’t include the rm -rf . I just write the subdommain scanner. I want to run the script and save it as the output. But with above script. It is not saving data. I want to save it in djago database as data. How can I link model , url and views to add html source code?