Thursday, 7 February 2019

Django Celery task to copy file from remote host using SCP and SSHPASS



@task()
def copyBkpFromJenkinstoDjango():
       ip = ''
       port = ""
       username = ""
       password = ""
       cmd = "sshpass -p '<password>' scp -r root@<remoteIP>:/root/networkBackups /root/Django"
       #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

Wednesday, 6 February 2019

Moving all files from one directory to another using Python


import shutil
import os
source = '/path/to/source_folder'
dest1 = '/path/to/dest_folder'

files = os.listdir(source)

for f in files:
        shutil.move(source+f, dest1)

Tuesday, 5 February 2019

Python script to trigger ansible playbook via SSH using paramiko SSH Client



       cmd = "ansible-playbook " +  <playbookname> + " -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

Python Script to create File and append 10 dummy lines on every function call

def createFolder():
   try:
        if not os.path.exists(directory):
            os.makedirs(directory)
            return 'FolderCreated'
            return 'FolderNotCreated'

     f = open("/home/raghu/Desktop/raghu1234.txt","a+")

     for i in range(10):
        f.write("This is the line %d\r\n" % (i+1))

     f.close()

# FunctionCall
createFolder()

Get Result from Jenkins Job via API



                output = 'curl http://<jenkinsUserName>:<jenkinsPassword>@<jenkinsIP>:<jenkinsPort>/job/<JobName>/<BuildNumber>/consoleText'

                jobout = subprocess.check_output(output, shell=True)

                print (jobout)

Trigger a ansible playbook via jenkins using jenkins API




 'curl -d ' + finalString + ' -i -X POST http://admin:<adminpassword>@<JenkinsIP>:<PortNumber>/job/<JobName>/buildWithParameters -H "Jenkins-Crumb:<crumbID>"'



finalString =   inputs for the ansible script in this format example - "ticketnumber=d" -d "deviceType=yj" -d "createnewpool=kug" -d "server=k" -d "node=y" -d "poolname=y" -d "port=y" -d "modificationtype=yy" -d "partition=yy" -d "lb_method=yy" -d "slowramptime=yy"

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

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...