Пример #1
0
def getFiles(extension,password):
    try:
        # anonymous login so no password
        if "conf" in extension:
            # set the ftp path to the config files location
            path = getIniConfPath()
        else:
            # set the ftp path to the os files location
            path = getOsPath()
        address = getFtpAddress()
        username = getFtpUsername()
        # Log into FTP
        ftp = FTP(address)
        ftp.login(username,password)
        ftp.cwd(path)

        # get list of all the files in the directory
        files = ftp.nlst()
        actualFiles = []
        # add all the files with the appropriate extension to the list
        for index in range(len(files)):
            if extension in files[index]:
                actualFiles.append(files[index])
        ftp.quit()
        return actualFiles

    except Exception as e:
        print(str(e))
        return [] #just return empty list no need for error
Пример #2
0
 def getContentsOfFile(self):
     returnString = StringIO()  # IO object to be written to like a file
     ftpAddress = getFtpAddress()
     selectedFile = self.fileToPull
     ftp = FTP(ftpAddress)
     ftp.login(getFtpUsername(), self.ftpPassword)
     # write contents of file to object with new lines
     ftp.retrlines('RETR ' + selectedFile,
                   lambda line: returnString.write(line + '\n'))
     self.pulledFilesContents = returnString.getvalue()
Пример #3
0
def checkFTPConnection(ftpPassword):
    try:
        ftpAddr = getFtpAddress()
        ftp = FTP(ftpAddr)
        username = getFtpUsername()
        ftp.login(username, ftpPassword)
        ftp.nlst()
        ftp.quit()
        return True
    except:
        return False
Пример #4
0
def addToRepo(callingWindow):

    #Set variable values
    dbAddress = getDatabaseAddress()
    db = getDatabase()
    configTable = getDatabaseTable()
    dbUsername = getDatabaseUsername()
    dbPassword = callingWindow.databasePassword
    ftpUsername = getFtpUsername()
    ftpPassword = callingWindow.ftpPassword
    configName = callingWindow.selectedConfig.currentText()
    deviceSerial = ""
    configFile = callingWindow.fileToPush
    commitTitle = callingWindow.commitTitle.text()
    commitDesc = callingWindow.commitDescription.toPlainText()
    time = datetime.utcnow().strftime('%d-%m-%Y %H:%M:%S.%f')[:-4]
    newFileName = time.replace(":", "-")[:-3]
    newFileName = newFileName.replace(" ", "_") + ".conf"

    # Get current Config details
    getSerial = ("select serial from " + configTable + " where name=\"" +
                 configName + "\" and isPrimary=\"1\"")
    try:
        conn = None

        conn = pymysql.connect(host=dbAddress,
                               port=3306,
                               user=dbUsername,
                               passwd=dbPassword,
                               db=db)
        cursor = conn.cursor()
        cursor.execute(getSerial)
        deviceSerial = cursor.fetchone()[0]
        conn.close()
    except Exception as e:
        print("Serial couldn't be recovered." + str(e))
        if not conn is None:
            conn.close()

    #Upload file to the FTP Server
    ftpAddress = getFtpAddress()
    path = getConfPath()
    fileContents = ""
    try:
        conn = None
        ftp = None

        #chck if conf file
        if not "conf" in configFile:
            messageWindow("Error!",
                          "Make sure that you are uploading a .conf file,",
                          True)
            return False
        else:
            # Log into FTP
            ftp = FTP(ftpAddress)
            ftp.login(ftpUsername, ftpPassword)
            ftp.cwd(path)
            #Upload the file
            file = open(configFile, "rb")
            ftp.storlines('STOR ' + newFileName, file)
            ftp.close()
            file.close()

            # Get current config info
            updateCurentRecord = ("update " + configTable + " set " +
                                  "isPrimary=\"0\"" + " where name=\"" +
                                  configName + "\" and isPrimary=\"1\"")

            # Send new config details
            newFileNamePath = path + newFileName
            addNewRecord = (
                "insert into " + configTable +
                "(name,serial,user,timestamp,path,title,description,isprimary)"
                + " values (\"" + configName + "\", \"" + deviceSerial +
                "\",\"" + dbUsername + "\",\"" + time + "\",\"" +
                newFileNamePath + "\", \"" + commitTitle + "\", \"" +
                commitDesc + "\", 1)")

            # Push the data to the database

            conn = pymysql.connect(host=dbAddress,
                                   port=3306,
                                   user=dbUsername,
                                   passwd=dbPassword,
                                   db=db)
            cursor = conn.cursor()
            cursor.execute(updateCurentRecord)
            cursor.execute(addNewRecord)
            conn.commit()
            conn.close()
            return True

    except Exception as e:
        print(str(e))
        if not conn is None:
            conn.close()
        if not ftp is None:
            ftp.close()
        return False
Пример #5
0
    def connect_session(self, portNo, ftpPassword,consolePassword, databasePassword,devicePassword ,OsFile, configFile, willClone, updateGui):
        try:
            # Get values from user input
            ftpAddress = getFtpAddress()
            osFile = getOsPath() + OsFile
            confPath = getIniConfPath() + configFile
            username = getConsoleName() + ":" + str(portNo)
            hostname = getConsoleAddress()

            # Connect to the console server
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname, 22, username, consolePassword)
            term = ssh.invoke_shell()

            # Log into the device
            if updateGui:
                self.trigger.emit(11)
            waitForTerm(term, 60, "login:"******"set cli screen-length 0")

            # Get device serial number
            originalVersion = send_command(term, "show system software")
            xml = send_command(term, "show chassis hardware | display xml")
            serialNo = parse_xml_serial(xml)

            # Push serial number to the database
            updatedTime = pushSerial(getDatabaseAddress(), getDatabaseUsername(), databasePassword,getDatabase(), configFile, serialNo, confPath)
            if updateGui:
                self.trigger.emit(44)

            # Upgrade JUNOS
            ftpDetails = getFtpUsername() + ":" + ftpPassword + "@" + ftpAddress
            upgradeOs = "request system software add ftp://" + ftpDetails + osFile + " no-copy no-validate reboot"
            send_command(term, upgradeOs)

            # Wait for the device to reboot
            if updateGui:
                self.trigger.emit(55)
            print("upgrading")
            waitForTerm(term, 180, "login:"******"finished")
            waitForLogin(term,devicePassword)
            if updateGui:
                self.trigger.emit(66)
            waitForTerm(term, 2, "root")
            send_command(term, "set cli screen-length 0")

            # Snapshot to the backup partition
            if willClone:
                send_command(term, "request system snapshot media internal slice alternate")
            time.sleep(15)
            waitForTerm(term, 60, "root")

            # Check the version of JUNOS
            updatedVersion = send_command(term, "show system software")
            if updateGui:
                self.trigger.emit(77)

            # Start applying a configuration to the device
            if not updatedVersion == originalVersion:
                send_command(term, "configure")
                time.sleep(2)
                send_command(term, "delete")
                time.sleep(2)
                send_command(term, "yes")
                time.sleep(2)
                # Get the configuration file from the FTP Server
                send_command(term, "load set ftp://" + ftpAddress + confPath)
                time.sleep(2)
                xml = send_command(term, "show snmp location | display xml")
                time.sleep(2)

                # Get device deployment location (rollNo)
                rollNo = ""
                try:
                    xml = xml.split("<rpc-reply")[1]
                    xml = "<rpc-reply" + xml
                    xml = xml.split("</rpc-reply>")[0]
                    xml += "</rpc-reply>"
                    xmlDict = xmltodict.parse(xml)
                    rollNo = xmlDict['rpc-reply']['configuration']['snmp']['location']
                except:
                    print ("No location data.")
                time.sleep(5)

                # Push roll number (deployment location) to the database
                pushRollNo(getDatabaseAddress(), getDatabaseUsername(), databasePassword,getDatabase(),rollNo, updatedTime)
                time.sleep(5)

                #Set device root password
                send_command(term,"set system root-authentication plain-text-password")
                send_command(term,devicePassword)
                send_command(term,devicePassword) #confirm password
                time.sleep(2)

                #Commit the current configuration
                send_command(term, "commit and-quit")
                waitForTerm(term, 60, "root@")
                send_command(term, "request system autorecovery state save")
                time.sleep(30)
                send_command(term, "request system configuration rescue save")
                time.sleep(30)

                # Update the progress bar
                if updateGui:
                    self.trigger.emit(88)

                # Reboot the device
                send_command(term, "request system reboot")
                time.sleep(2)
                send_command(term, "yes")

                #Wait for the device to boot
                waitForTerm(term, 180, "login:"******"root")
                xml = send_command(term, "show configuration snmp location | display xml")
                time.sleep(5)

                # Get device deployment location (rollNo) - in order to perform a final check
                checkRollNo=""
                try:
                    xml = xml.split("<rpc-reply")[1]
                    xml = "<rpc-reply" + xml
                    xml = xml.split("</rpc-reply>")[0]
                    xml += "</rpc-reply>"
                    xmlDict = xmltodict.parse(xml)
                    checkRollNo = xmlDict['rpc-reply']['configuration']['snmp']['location']
                except:
                    print("No location data.")

                if rollNo == checkRollNo:
                    print("Deployment successful.")
                    send_command(term, "request system halt in 0")
                    time.sleep(2)
                    send_command(term, "yes")

                if updateGui:
                    self.trigger.emit(100)
            else:
                print("OS wasn't updated correctly, Not applying config, Shutting down")

        except paramiko.ssh_exception.BadHostKeyException:
            secondaryWindows.messageWindow("Host Key Error!", "Server’s host key could not be verified", True)
        except paramiko.ssh_exception.AuthenticationException:
            secondaryWindows.messageWindow("Authentication Error!", "Authentication failed, Check your details and try again", True)
        except paramiko.ssh_exception.SSHException:
            secondaryWindows.messageWindow("Unknown Error!", "Unknown error connecting or establishing an SSH session", True)
        except socket.gaierror as e:
            print(str(e))