def startDatabaseGrabber(self): # connect to database to pull down primary files thread = DatabaseGrabber(self.window) thread.setup(self, getDatabaseAddress(), getDatabaseUsername(), self.databasePassword, getDatabase()) thread.trigger.connect(self.fillComboBox) thread.start()
def checkDatabaseConnection(dbPswd): dbAddr = getDatabaseAddress() dbUsr = getDatabaseUsername() connection = None cursor = None try: connection = pymysql.connect(host=dbAddr, port=3306, user=dbUsr, passwd=dbPswd, db='runbook') cursor = connection.cursor() cursor.execute("SELECT VERSION()") response = cursor.description if response: # if we have anything in this request then we are connected and able to send and receive cursor.close() connection.close() return True else: cursor.close() connection.close() return False except pymysql.OperationalError: return False except: # any issue assume no clear connection to database if not cursor is None: cursor.close() if not connection is None: connection.close() return False
def getDatabaseListing(dbPswd): dbAddr = getDatabaseAddress() dbUsr = getDatabaseUsername() database = getDatabase() table = getDatabaseTable() conn = None cursor = None try: conn = pymysql.connect(host=dbAddr, port=3306, user=dbUsr, passwd=dbPswd, db=database) cursor = conn.cursor() cursor.execute("SELECT * FROM "+ table+" limit 100;") # return a limit of 100 listings response = cursor.fetchall() if response: # if we've returned something cursor.close() conn.close() return response else: cursor.close() conn.close() return None except pymysql.OperationalError: return None except: # any issue assume no clear connection to database if not cursor is None: cursor.close() if not conn is None: conn.close() return "Error"
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
def startHistoryGrabber(self, selectedFile): thread = SelectedFileGrabber(self.window) thread.setup(self, getDatabaseAddress(), getDatabaseUsername(), self.databasePassword, getDatabase(), selectedFile) thread.trigger.connect(self.updateDots) thread.start()
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))