from django.shortcuts import render,redirect
from pymetasploit3.msfrpc import MsfRpcClient
# Create your views here.
import os


def option(request):
    # print(request.session['exploit'])
    client = MsfRpcClient('pass',ssl=False)
    exploit = client.modules.use('exploit',request.session['exploit'])
    return render(request,'options.html',{'missing':exploit.missing_required,'desc':exploit.description,})

def execute_exploit(request):
    if request.method == 'POST':
#        payload = request.POST['payload']
        client = MsfRpcClient('pass',ssl=False)
        exploit = client.modules.use('exploit',request.session['exploit'])
#        request.session['command']+=f'set PAYLOAD {payload};'
        for i in exploit.missing_required:
            if i == 'RHOSTS':
                exploit[i] = request.session['IP']
                request.session['command']+=f"set RHOSTS {exploit[i]} ;set RPORT {request.session['port']}; "

                continue
            if i == 'SESSION':
                request.session['command']+=f"set SESSION {str(exploit[i])};"

                continue
            exploit[i] = request.POST[i]
        job_id = exploit.execute()
        cm = f"msfconsole -x '{request.session['command']};exploit;'"
        print(request.session['command'])
        os.system("gnome-terminal -- "+cm)
        return render(request,'job_id.html',{'job_id':job_id,'client':client.sessions.list})
