Tuesday, 5 February 2019

Django to trigger ansible playbook via (python paramiko.SSHClient()) SSH (take input from template and display result in other template )

def backupPage(request):
        my_form3 = Backup()
        if request.method == 'POST' and 'NetworkBackup' in request.POST:

            my_form3 = Backup(request.POST)
            if my_form3.is_valid():
                ticketnumber = my_form3.cleaned_data['ticketNumber']
                ip = my_form3.cleaned_data['ansibleServerIP']
                port = my_form3.cleaned_data['ansibleServerPort']
                username = my_form3.cleaned_data['ansibleServerUsername']
                password = my_form3.cleaned_data['ansibleServerPassword']
                cmd = my_form3.cleaned_data['playbookFullPath']
                minutes = my_form3.cleaned_data['TimerInMinutes']
                #occurence = my_form3.cleaned_data['TimerInMinutes']
                f = open("/home/raghu/Desktop/Backup/" + ticketnumber + ".txt","a+")
                f.write(ticketnumber + " " + ip + " " + port + " " + " " + username + " " + password + " " + cmd)
                f.close()
                time.sleep(5)
                latestFiles = glob.glob('/home/raghu/Desktop/Backup/*')
                latestFile = max(latestFiles, key=os.path.getctime)
                print (latestFile)

                a = schedule1()
                return render(request, "mail.html" , { 'form1': a })

                #schedule.every(minutes).minutes.do(schedule1)
                #while True:
                #    schedule.run_pending()
                #    time.sleep(1)

        return render(request, "backupPage.html" , { 'form3': my_form3 })

def schedule1():
       latestFiles = glob.glob('/home/raghu/Desktop/Backup/*')
       latestFile = max(latestFiles, key=os.path.getctime)
       #print latestFile
       #f.close()
       filename = latestFile;
       f = open(filename,"r")
       temp = f.read()
       words = temp.split()
       ip = words[1]
       port = words[2]
       username = words[3]
       password = words[4]
       cmd1 = words[5]
       cmd = "ansible-playbook " + cmd1 + " -vvvv"
       print (cmd)
       ssh=paramiko.SSHClient()
       ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
       ssh.connect(ip,port,username,password)
       stdin,stdout,stderr=ssh.exec_command(cmd)
       time.sleep(50)
       outlines=stdout.readlines()
       resp =''.join(outlines)
       print(resp)
       return resp

No comments:

Post a Comment

Git

1 git add ↳ It lets you add changes from the working directory into the staging area 2 git commit ↳ It lets you save a snapshot of currently...